【问题标题】:What does <T = {}> mean?<T = {}> 是什么意思?
【发布时间】:2021-11-16 21:51:48
【问题描述】:

我在文档中找到了这种通用类型: type GConstructor&lt;T = {}&gt; = new (...args: any[]) =&gt; T; https://www.typescriptlang.org/docs/handbook/mixins.html

该行上方只有一个简短的注释说这是一个通用约束。但它没有在通用约束的文档中描述: https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints

那么 是如何工作的呢?它强制执行哪些约束?

【问题讨论】:

  • 这能回答你的问题吗? In Typescript what does <T> mean?
  • 它不强制任何约束。这是一个可选的泛型类型参数,如果未指定,则默认值为 {}
  • 没有克里斯蒂安。 &lt;T = {}&gt;&lt;T&gt; 不一样

标签: typescript


【解决方案1】:

这不是generic constraint;那些使用extends 强制泛型类型参数可分配给其他类型:

// the type T must be assignable to {a: string}
type Foo<T extends { a: string }> = T;

type A = Foo<{ a: "hello" }> // {a: "hello"}
type B = Foo<Date> // error!

取而代之的是generic parameter default,如果您未指定或编译器无法推断类型参数,则编译器将使用该类型的后备类型:

// the type T will be {a: string, b: number} if you fail to specify it:
type Bar<T = { a: string, b: number }> = T;
type C = Bar<Date> // Date
type D = Bar // {a: string, b: number}

它们是独立的,但您可以同时使用它们来约束类型参数并提供默认值(必须可分配给约束本身):

// both
type Baz<T extends { a: string } = { a: string, b: number }> = T;
type E = Baz<{ a: "hello" }> // {a: "hello"}
type F = Baz<Date> // error!
type G = Baz // {a: string, b: number}

Playground link to code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-29
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    • 2016-03-09
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    相关资源
    最近更新 更多