[英]Typescript: issue with type intersection and type alias
Using Typescript 2.1.4 , I bumped into some weird compilation problem while using intersection types ( type1 & type2
) and type alias ( type Something<T> = ...
). 使用Typescript 2.1.4 ,在使用交集类型(
type1 & type2
)和类型别名( type Something<T> = ...
)时遇到了一些奇怪的编译问题。
To explain what I tried to achieve: I simply wanted to declare a type alias which represents the intersection of some defined object values (in this case the property id
of type string
) and of custom additional properties, all of them being optional. 为了解释我试图达到的目的:我只想声明一个类型别名,该别名表示一些定义的对象值(在这种情况下为
string
类型的属性id
)与自定义其他属性的交集,它们都是可选的。 This type uses the Typescript pre-defined Partial
type alias. 此类型使用Typescript预定义的
Partial
类型别名。
The following code compiles and works: 以下代码可以编译和运行:
export type StoreModelPartial<T> = {id:string} & T;
function test<T>(obj:StoreModelPartial<T>) {
console.log('TEST', obj);
}
console.log(test({
'id':'value',
'something':'value2'
}));
But when I try to use the Partial
type alias, I get a compilation error: 但是,当我尝试使用
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'
}));
I get this error: 我收到此错误:
Argument of type '{ 'id': string;
类型'{'id'的参数:字符串; 'something': string;
'something':字符串; }' is not assignable to parameter of type 'Partial<{ id: string;
}”不能分配给“ Partial <{id:string; } & T>
}&T>
Any idea? 任何想法?
Ah forget it, I think I figured it out by writing this question... And re-reading the error message of my code sample, which is clearer than the more complex part I was fighting with originally. 啊,算了吧,我想我是通过写这个问题来解决的……然后重新阅读我的代码示例的错误消息,这比我最初处理的更复杂的部分更清楚。
I had thought intersection and extension were somewhat the same, but nope. 我以为交集和扩展名有些相同,但是不行。
What I need is extends
: 我需要的是
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'
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.