打字稿:类型交集和类型别名的问题
Typescript: issue with type intersection and type alias
使用 Typescript 2.1.4,我在使用交集类型 (type1 & type2
) 和类型别名 (type Something<T> = ...
) 时遇到了一些奇怪的编译问题。
为了解释我试图实现的目标:我只是想声明一个类型别名,它表示一些定义的对象值的交集(在这种情况下 属性 id
类型 string
) 和自定义附加属性,所有这些都是可选的。
此类型使用 Typescript 预定义 Partial
类型别名。
以下代码可以编译并运行:
export type StoreModelPartial<T> = {id:string} & T;
function test<T>(obj:StoreModelPartial<T>) {
console.log('TEST', obj);
}
console.log(test({
'id':'value',
'something':'value2'
}));
但是当我尝试使用 Partial
类型别名时,出现编译错误:
export type StoreModelPartial<T> = Partial<{id:string} & T>;
function test<T>(obj:StoreModelPartial<T>) {
console.log('TEST', obj);
}
console.log(test({
'id':'value',
'something':'value2'
}));
我收到这个错误:
Argument of type '{ 'id': string; 'something': string; }' is not
assignable to parameter of type 'Partial<{ id: string; } & T>
有什么想法吗?
啊算了,我想我是通过写这个问题弄明白的……还有re-reading我的代码示例的错误信息,这比我最初与之抗争的更复杂的部分更清楚。
我原以为交集和外延有些相同,但不是。
我需要的是extends
:
export type StoreModelPartial<T extends {id?:string}> = Partial<T>;
function test<T>(obj:StoreModelPartial<T>) {
console.log('TEST', obj);
}
console.log(test({
'id':'value',
'something':'value2'
}));
使用 Typescript 2.1.4,我在使用交集类型 (type1 & type2
) 和类型别名 (type Something<T> = ...
) 时遇到了一些奇怪的编译问题。
为了解释我试图实现的目标:我只是想声明一个类型别名,它表示一些定义的对象值的交集(在这种情况下 属性 id
类型 string
) 和自定义附加属性,所有这些都是可选的。
此类型使用 Typescript 预定义 Partial
类型别名。
以下代码可以编译并运行:
export type StoreModelPartial<T> = {id:string} & T;
function test<T>(obj:StoreModelPartial<T>) {
console.log('TEST', obj);
}
console.log(test({
'id':'value',
'something':'value2'
}));
但是当我尝试使用 Partial
类型别名时,出现编译错误:
export type StoreModelPartial<T> = Partial<{id:string} & T>;
function test<T>(obj:StoreModelPartial<T>) {
console.log('TEST', obj);
}
console.log(test({
'id':'value',
'something':'value2'
}));
我收到这个错误:
Argument of type '{ 'id': string; 'something': string; }' is not assignable to parameter of type 'Partial<{ id: string; } & T>
有什么想法吗?
啊算了,我想我是通过写这个问题弄明白的……还有re-reading我的代码示例的错误信息,这比我最初与之抗争的更复杂的部分更清楚。
我原以为交集和外延有些相同,但不是。
我需要的是extends
:
export type StoreModelPartial<T extends {id?:string}> = Partial<T>;
function test<T>(obj:StoreModelPartial<T>) {
console.log('TEST', obj);
}
console.log(test({
'id':'value',
'something':'value2'
}));