Reputation: 591
type FruitName = 'apple' | 'banana';
interface Fruit {
name: FruitName;
}
const apple = {
'name': 'apple',
};
function test(fruit: Fruit) {
console.log(fruit.name);
}
function main() {
const name: FruitName = 'apple'; // this is ok
test(apple); // error TS2345: Argument of type '{ name: string; }' is not assignable to parameter of type 'Fruit'.type 'FruitName'
// Types of property 'name' are incompatible.
// Type 'string' is not assignable to type 'FruitName'.
}
main();
I couldn't figure out why apple is not assignable to Fruit.
But, 'apple' is assignable to name: FruitName.
What's difference of two?
Upvotes: 0
Views: 13934
Reputation: 19987
const apple = { 'name': 'apple' as const }
would work.
"apple"
alone is inferred as string
type, while "apple" as const
is inferred as "apple"
string literal type. String literal is subtype of string, not the other way around.
let appleString: string = "apple"
let appleLiteral: "apple" = "apple" as const
appleString = appleLiteral // ok
appleLiteral = appleString // error
Upvotes: 1