泛型类型中的extends和=有什么区别?

Nic*_*kiy 3 typescript

这两个函数有什么区别呢?两者的工作原理相同。我知道扩展如何在接口中工作,但我无法理解这里的差异

const func = <T extends string>(str: T): T => str 
Run Code Online (Sandbox Code Playgroud)
const func = <T = string>(str: T): T => str 
Run Code Online (Sandbox Code Playgroud)

Ale*_*yne 8

这些是非常不同的事情。


<T extends string>
Run Code Online (Sandbox Code Playgroud)

这是一个约束。这意味着它T必须是string或子类型string(即字符串文字)

const func = <T extends string>(str: T): T => str

func("A") // returns type "A" because "A" is a subtype of string
func<string>("A") // returns type string because the inference was overridden
func(123) // error 123 is not a subtype of string
Run Code Online (Sandbox Code Playgroud)

操场


<T = string>
Run Code Online (Sandbox Code Playgroud)

这是默认类型。在这种情况下T不受约束,但如果省略string则用作 的类型T

const func = <T = string>(str: T): T => str

func("A") // returns type "A" because "A" is a inferred for T
func<string>("A") // returns type string because the inference was overridden
func(123) // returns type 123 because 123 is inferred as the type for T
Run Code Online (Sandbox Code Playgroud)

操场

默认类型在此示例中没有多大意义,因为当您省略默认类型时,它是由参数推断出来的。让我们看一个不同的例子:

type MyType<T = string> = { value: T }
type TestA = MyType<number> // equivalent to { value: number }
type TestB = MyType // equivalent to { value: string }
Run Code Online (Sandbox Code Playgroud)

操场

请注意如何TestB省略通用项,而string使用默认值。

T extends string但是,在和 的TestA情况下TestB都是类型错误:

type MyType<T extends string> = { value: T }
type TestA = MyType<number> // type error: number does not extend string
type TestB = MyType // type error: missing generic parameter
Run Code Online (Sandbox Code Playgroud)

操场