是否有其他语言支持 Typescript 的映射类型和条件类型功能?

Seb*_*eth 7 typescript

我一直在使用 Typescript 的类型映射和条件类型功能,并发现它们在为我的代码构建开发人员友好的 API 方面非常独特且具有开创性。我的印象是它们是相当独特的功能,但我想我会问是否还有其他语言具有功能等效性?还是 Typescript 是唯一的?

小智 0

TypeScript 的类型系统具有强大的映射和条件类型,确实是静态类型语言中最先进的之一。

然而,TypeScript 并不是唯一具有高级类型系统功能的语言。虽然确切的语法和行为可能有所不同,但其他几种语言提供的表达类型系统具有可以实现类似结果的功能。

Scala类型系统极其丰富。类型类、路径相关类型和隐式转换等功能提供了非常富有表现力的类型级编程。Scala 3 引入了更高级的功能,例如依赖函数类型和匹配类型,这让人想起 TypeScript 的条件类型。

type Elem[X] = X match {
case List[t] => tcase Array[t] => t
}

def firstElement[X](xs: X)(using ev: X <:< Iterable[Elem[X]]): Elem[X] = xs.head
Run Code Online (Sandbox Code Playgroud)

Haskell是一种纯函数式语言,具有强大且富有表现力的类型系统。Haskell 中的类型类是一种定义可处理各种类型的操作的方法。Haskell 还具有 GADT(广义代数数据类型)和类型族等功能,可实现高级类型级计算。

class Printable a where
  toString :: a -> String
instance Printable Int where
  toString = show

instance Printable Bool where
  toString = show
Run Code Online (Sandbox Code Playgroud)

Idris是一种具有依赖类型的通用函数式编程语言。这意味着类型可以依赖于值,从而可以实现令人难以置信的富有表现力的类型。这超越了主流语言中的大多数其他类型系统。

data Vect : Nat -> Type -> Type where
  Nil : Vect 0 a
  (::) : (x : a) -> (xs : Vect n a) -> Vect (n + 1) a
Run Code Online (Sandbox Code Playgroud)

Kotlin虽然在类型系统方面不如 Scala 表现力强,但确实具有密封类、扩展函数和类型安全构建器等功能,使创建开发人员友好的 API 成为一种乐趣。

sealed class Result<out T, out E>
data class Success<T>(val value: T) : Result<T, Nothing>()
data class Error<E>(val error: E) : Result<Nothing, E>()
Run Code Online (Sandbox Code Playgroud)

Rust的类型系统虽然目标不同(专注于内存安全),但仍然非常具有表现力。Rust 中的特征和关联类型可用于创建灵活且类型安全的抽象。

trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
}

struct Counter;
impl Iterator for Counter {
    type Item = u32;

    fn next(&mut self) -> Option<u32> {
        // ... implementation ...
    }
}
Run Code Online (Sandbox Code Playgroud)

Swift面向协议的设计及其泛型支持也有助于创建富有表现力的类型安全 API。关联类型和协议扩展等功能可用于创建灵活的抽象。

protocol Container {
    associatedtype ItemType
    mutating func append(_ item: ItemType)
    var count: Int { get }
    subscript(i: Int) -> ItemType { get }
}
Run Code Online (Sandbox Code Playgroud)

F#拥有一个富有表现力的类型系统,具有类型提供程序等功能,允许您根据外部数据源即时生成类型。

type dbSchema = SqlDataProvider<"""Data Source=.;Initial Catalog=MyDatabase;Integrated Security=True;""">

let db = dbSchema.GetDataContext()

let firstCustomerName = query {
    for customer in db.Customers do
    select customer.Name
    head
}
Run Code Online (Sandbox Code Playgroud)