【问题标题】:Typescript: take a type and return a union type in a generic interface打字稿:在泛型接口中获取一个类型并返回一个联合类型
【发布时间】:2016-07-11 12:45:09
【问题描述】:
想象一个简单的CollectionStore,它具有创建和更新记录的方法。 create() 接受一组属性并返回添加了id 属性的同一组。 update 接受相同结构的集合,但需要定义 id 属性。
如何在 Typescript 中表示 create() 函数接受某种类型 T 并返回 T & {id: string} ?
我希望模式可以这样表达:
interface CollectionStore<T> {
updateRecord(T & {id: string}): void;
createRecord(T): T & {id: string};
}
但是上面的代码是无效的。请帮忙=)
【问题讨论】:
标签:
generics
typescript
interface
unions
【解决方案1】:
您使用联合类型的方式是正确的,但是您未能为函数参数提供名称,这就是您收到错误的原因,应该是:
interface CollectionStore<T> {
updateRecord(record: T & { id: string }): void;
createRecord(record: T): T & { id: string };
}
然后:
interface MyRecord {
key: string;
}
let a: CollectionStore<MyRecord> = ...;
a.updateRecord({ key: "key", id: "id" });
a.createRecord({ key: "key" });
(code in playground)
您的另一个选择是只为记录提供一个基本接口,其中id 属性是可选的:
interface Record {
id?: string;
}
interface CollectionStore<T extends Record> {
updateRecord(record: T): void;
createRecord(record: T): T;
}
但随后您将无法强制 updateRecord 返回具有 id 的对象。