[英]Typescript: take a type and return a union type in a generic interface
想象一个简单的CollectionStore
,其中包含用于创建和更新记录的方法。 create()
接受一组属性,并返回添加了id
属性的同一组属性。 update
接受具有相同结构的集合,但需要定义id
属性。
我如何在Typescript中表达create()
函数接受某种类型T
并返回T & {id: string}
?
我希望模式可以这样表达:
interface CollectionStore<T> {
updateRecord(T & {id: string}): void;
createRecord(T): T & {id: string};
}
但是,上面的代码无效。 请帮忙=)
您正确地使用了联合类型,但是您未能为函数params提供名称,这就是为什么会出现错误的原因,它应该是:
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" });
( 操场上的代码 )
您还有另一个选择,就是为记录提供一个基本接口,其中id
属性是可选的:
interface Record {
id?: string;
}
interface CollectionStore<T extends Record> {
updateRecord(record: T): void;
createRecord(record: T): T;
}
但是,您将无法强制执行updateRecord
返回具有ID的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.