这两处代码有什么不同

第一段

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 里面 我们经常用到那种呢?前端大佬给点指示

每天一点小知识,到那都是大佬,哈哈
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
最佳答案

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

在了解你所谓的 「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 方法不能接收一个字符串类型的参数。


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

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

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

1年前 评论
JinBB 1年前
raybon (楼主) 1年前
讨论数量: 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 方法不能接收一个字符串类型的参数。


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

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

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

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

php?

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

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

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

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

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

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

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

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