【问题标题】:TypeScript reports non-existent properties in generic functionTypeScript 报告泛型函数中不存在的属性
【发布时间】:2016-07-02 12:13:17
【问题描述】:

考虑一下 TypeScript 中的以下泛型函数:

interface Foo { id: string; }
const foo = <Foo>{id: 'bar'};
function baz<T>(x: T) { console.log(x.id); }
baz(foo);

这不会编译:

test.ts(6,17): error TS2339: Property 'id' does not exist on type 'T'.

在我看来,TypeScript 应该能够处理这种情况。如果不能,那么我必须这样做:

interface IHasId { id: string; }
interface Foo extends IHasId { }
const foo = <Foo>{id: 'bar'};
function baz<T>(x: IHasId) { console.log(x.id); }
baz<Foo>(foo);

是否有任何替代或更惯用的方法来处理这种情况?

【问题讨论】:

  • 改用any

标签: generics typescript


【解决方案1】:

有道理,第一个示例无法编译。 Typescript 是关于添加类型检查的。如果你想禁用它,你可以使用any,但是为什么在这种情况下使用泛型呢?

如果要对泛型类型定义约束,可以这样:

function baz<T extends IHasId>(x: T) { console.log(x.id); }

顺便说一句,约束可以内联定义:

function baz<T extends { id: string; }>(x: T) { console.log(x.id); }

【讨论】:

    猜你喜欢
    • 2021-07-02
    • 2020-04-12
    • 2019-03-31
    • 2016-12-19
    • 1970-01-01
    • 2020-03-23
    • 2019-02-13
    • 2019-05-29
    • 2020-07-26
    相关资源
    最近更新 更多