这两处代码有什么不同

第一段

interface GenericIdentityFn {
    <T>(arg: T): T;
}

function identity<T>(arg: T): T {
    return arg;
}

let myIdentity: GenericIdentityFn = identity;

第二段:

interface GenericIdentityFn<T> {
    (arg: T): T;
}

function identity<T>(arg: T): T {
    return arg;
}

let myIdentity: GenericIdentityFn<number> = identity;

在ts 里面 我们经常用到那种呢?前端大佬给点指示

每天一点小知识,到那都是大佬,哈哈
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
最佳答案

先说结论,用第二种,第一种没意义。

在了解你所谓的 「T」之前,建议你先去学一一下 Java 的泛型,理念都是相通的。

先说第一种

interface GenericIdentityFn {
    <T>(arg: T): T;
}

function identity<T>(arg: T): T {
    return arg;
}

let myIdentity: GenericIdentityFn = identity;

interface 并没有对对象属性做约束,在没有 的约束时,默认是属性的值可以是 any。所以第一种的接口约束没意义。


第二种

interface GenericIdentityFn<T> {
    (arg: T): T;
}

function identity<T>(arg: T): T {
    return arg;
}

let myIdentity: GenericIdentityFn<number> = identity;

在声明 interface 时指定必须传入一个泛型 GenericIdentityFn<T> 以便使用它来约束对象属性的类型。

所以在赋值时必须要声明变量类型,也就是

let myIdentity: GenericIdentityFn<number> = identity; // number 就是声明了泛型的类型

最后说一下区别 第一种

myIndentity('test');
myIndentity(1234);

不论向 identity 方法传入什么参数,都是可以的,因为 interface 没有加类型约束。

第二种

myIndentity('test'); // error 类型错误
myIndentity(1234); // 正确

因为第二种的 interface 有泛型约束,而在声明变量时传入的变量类型是 number ,所以 myIndentity 方法不能接收一个字符串类型的参数。


最后再说简单一下什么是泛型?

泛型就好比老师留的作文作业,让你写一篇作为关于变量的,文体不限(诗歌、散文、论文)都可以。但不能既是诗歌又是散文,而且你也必须要写。

代入到编程中就是:泛型就是一种未声明变量类型的类型,就好像一个空杯子,你装牛奶进去就是一杯牛奶,装可乐进去就是一杯可乐。但是不能混装。

2年前 评论
JinBB 2年前
raybon (楼主) 2年前
讨论数量: 11

先说结论,用第二种,第一种没意义。

在了解你所谓的 「T」之前,建议你先去学一一下 Java 的泛型,理念都是相通的。

先说第一种

interface GenericIdentityFn {
    <T>(arg: T): T;
}

function identity<T>(arg: T): T {
    return arg;
}

let myIdentity: GenericIdentityFn = identity;

interface 并没有对对象属性做约束,在没有 的约束时,默认是属性的值可以是 any。所以第一种的接口约束没意义。


第二种

interface GenericIdentityFn<T> {
    (arg: T): T;
}

function identity<T>(arg: T): T {
    return arg;
}

let myIdentity: GenericIdentityFn<number> = identity;

在声明 interface 时指定必须传入一个泛型 GenericIdentityFn<T> 以便使用它来约束对象属性的类型。

所以在赋值时必须要声明变量类型,也就是

let myIdentity: GenericIdentityFn<number> = identity; // number 就是声明了泛型的类型

最后说一下区别 第一种

myIndentity('test');
myIndentity(1234);

不论向 identity 方法传入什么参数,都是可以的,因为 interface 没有加类型约束。

第二种

myIndentity('test'); // error 类型错误
myIndentity(1234); // 正确

因为第二种的 interface 有泛型约束,而在声明变量时传入的变量类型是 number ,所以 myIndentity 方法不能接收一个字符串类型的参数。


最后再说简单一下什么是泛型?

泛型就好比老师留的作文作业,让你写一篇作为关于变量的,文体不限(诗歌、散文、论文)都可以。但不能既是诗歌又是散文,而且你也必须要写。

代入到编程中就是:泛型就是一种未声明变量类型的类型,就好像一个空杯子,你装牛奶进去就是一杯牛奶,装可乐进去就是一杯可乐。但是不能混装。

2年前 评论
JinBB 2年前
raybon (楼主) 2年前

php?

2年前 评论
raybon (楼主) 2年前

你可以给interface加上另一个方法,返回一个不是T的类型,再看看两者的区别。

2年前 评论
raybon (楼主) 2年前

我喜欢用第二段书写上感觉和Java很像哈

2年前 评论
raybon (楼主) 2年前

php社区的人才真多,什么都会。Java,go,ts。

2年前 评论
raybon (楼主) 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!