Reputation: 3273
Using Typescript 2.1.4, I bumped into some weird compilation problem while using intersection types (type1 & type2
) and type alias (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.
This type uses the Typescript pre-defined Partial
type alias.
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:
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; 'something': string; }' is not assignable to parameter of type 'Partial<{ id: string; } & T>
Any idea?
Upvotes: 0
Views: 535
Reputation: 3273
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
:
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'
}));
Upvotes: 1