Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【每日一题】- 2020-09-02 - type A<T> = (x:T) => T; type B = <T>(x:T) => T; 的区别 #148

Closed
azl397985856 opened this issue Sep 2, 2020 · 3 comments

Comments

@azl397985856
Copy link
Owner

azl397985856 commented Sep 2, 2020

在TS 中,如下两种写法有什么区别?

写法一:

type A<T> = (x:T) => T;

写法二:

type B = <T>(x:T) => T;
@suukii
Copy link

suukii commented Sep 2, 2020

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 会根据参数来进行类型推导。

个人理解大概就是这样吧,名词用得可能不十分准确。

@azl397985856
Copy link
Owner Author

azl397985856 commented Sep 2, 2020

结论

  • type A 声明一个泛型
  • type B 声明一个非泛型

解释

type A

type A 声明一个泛型,也就是说你可以:

A<string>
A<number>
...

这样使用,因为它是一个泛型。而且你必须这么用,比如如下代码是不合法的:

const identity3:A = (x) => {
    return x
}

这样才合法:

const identity3:A<string> = (x) => {
    return x
}

type A<T = 默认类型>

但是我可以这样声明一个泛型:

type A<T = string> = (x:T) => T;

这个时候是可以的:

const identity3:A = (x) => {
    return x
}

type B = (x:T) => T;

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
}

@stale
Copy link

stale bot commented Nov 1, 2020

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.

@stale stale bot added the stale label Nov 1, 2020
@stale stale bot closed this as completed Nov 8, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants