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?
CodePudding user response:
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