Closed azl397985856 closed 3 years ago
type A<T> = (x: T) => T
const fn1: A<string> = (x) => x
fn1('hello')
type B = <T>(x: T) => T;
const fn2: B = x => x;
fn2<string>('world')
fn2(17)
fn2(null)
A
是一个泛型,用于生成一个新的类型,使用 A<Type>
语法来生成新的类型。
B
是一个函数签名,<T>
可以在调用函数的时候传入,也可以省略,TS 会根据参数来进行类型推导。
个人理解大概就是这样吧,名词用得可能不十分准确。
type A
A<string>
A<number>
...
这样使用,因为它是一个泛型。而且你必须这么用,比如如下代码是不合法的:
const identity3:A = (x) => {
return x
}
这样才合法:
const identity3:A<string> = (x) => {
return x
}
但是我可以这样声明一个泛型:
type A<T = string> = (x:T) => T;
这个时候是可以的:
const identity3:A = (x) => {
return x
}
type B 声明一个非泛型,也就是说你不能像使用泛型一样使用它:
const identity5:C<string> = (x) => {
return x
}
你只能:
const identity5:C = (x) => {
return x
}
这会造成以下代码报错,尽管逻辑上似乎行得通:
const identity5:C = (x:string) => {
return '1'
}
TS 4.0.2 报错:Type '(x: string) => string' is not assignable to type 'C'. Types of parameters 'x' and 'x' are incompatible. Type 'T' is not assignable to type 'string'.(
你唯一能做的就是类似这样写代码,即让 TS 推导。
const identity5:C = (x) => {
return x
}
identity5('5')
type A<T> = (x:T) => T;
type B<T = string> = (x:T) => T;
type C = <T>(x:T) => T;
function identity(x: string):string {
return x
}
const identity2:A<string> = (x) => {
return x
}
const identity3:B = (x) => {
return x
}
const identity4:B<string> = (x) => {
return x
}
const identity5:C = (x) => {
return x
}
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
在TS 中,如下两种写法有什么区别?
写法一:
写法二: