Reputation: 35
The following code looks correct to me, however TypeScript reports an error:
type AorB = 'a' | 'b';
interface Container {
aorb: AorB,
};
function example<T>(t: T): T {
return t;
}
const aorb: AorB = example({ aorb: 'a' });
/*
Type '{ aorb: string; }' is not assignable to type 'AorB'.
Type '{ aorb: string; }' is not assignable to type '"b"'.
*/
It looks as though the captured type is { aorb: string }
rather than { aorb: AorB }
.
What's the best way to prevent this?
See it in the TypeScript playground
Upvotes: 0
Views: 71
Reputation: 25790
Your AorB
type is a string, but you passed an object to example
. It should be either:
const aorb: AorB = example('a');
or
const container: Container = example({ aorb: 'a' as 'a' });
Upvotes: 3