Here is the code:
type User = {
id: number;
kind: string
}
function m<T extends User>(u: T): Partial<T> {
return {id: 1}
}
Since {id:1} is of type {id:number}, which is a subset of T, the code should work normally. But it throws an error saying that "Type '{ id: 1; }' is not assignable to type 'Partial<T>'."
I can't figure out why the type infered result of {id:1} is {id:1} itself instead of {id:number}. But anyway, I can assert that it actually is of type {id:number}, like this:
type User = {
id: number;
kind: string
}
function m<T extends User>(u: T): Partial<T> {
return {id: 1} as {id: number}
}
But still, it again throws an new error saying that "Type '{ id: number; }' is not assignable to type 'Partial<T>'". Strangely, isn't {id: number} a subset of T?
So here I have several questions:
Why the type infered result of
{id:1}is{id:1}itself instead of{id:number}?Why it still throws an error even if I have asserted that
{id:1}is of type{id: number}?How can I make the code work normally?