当编写像商店这样的字典的接口时,我想区分数据模型和商店中的项目,即id和模型。我想添加模型本身不使用字段的约束id
在他们的界面中,但我不知道该怎么做。
type Item<T> = T & {id: string}
// T is type of model
// Item<T> is type of objects in the store, use id as primary key
以下函数是简化版,用于在商店中添加新商品
function add<T>(model: Item<T>): T {
const id = uuid();
const result = {...model, id};
store.push(result);
return result;
}
最好添加一些约束T
that T
不具有id
财产,否则T
会是一样的Item<T>
,同时id
in Item<T>
不是同一个T
,这会导致错误。
总之,我需要这样的类型
type Item<T extends "The type which allow any type without property id: string"> = T & {id : string}
我尝试过以下方法:
type T0 = Exclude<any, {id: string}>; // any
type T1 = Exclude<{}, {id: string}>; // {}
type SafeModel<T extends Exclude<T, {id: string}>>; //circular constrain
它们都不起作用。
我想要类似的东西
type Model // define like this
const v0: Model = {name: 'someName'} // ok
const v2: Model = {value: 123, id: 'someId'} //ok
const v1: Model = {name: 'someName', id: 'someId'} //error
或者绕过循环约束来定义类型的方法,它允许定义
type Model<T> = T extends { id: string } ? never: T;
type Item<T extends Model<T>> = T & { id: string }