关于typescript里的类型接口?

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

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

let myIdentity: GenericIdentityFn = identity;

新手目前正在学ts,但是一直不明白为什么接口已经定义了参数的类型,function里还要再写一遍?

阅读 2.6k
1 个回答

你可以这么写

let myIdetity: GenericIdentityFn = (arg) => {
    return arg;
}

你在定义identity时并没表示这个函数是实现了GenericIdentityFn的,所以你得自己写一遍类型参数。
实际上function xxx() {}的写法也无法声明其实现了什么

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题