【发布时间】: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