gpt4 book ai didi

javascript - typescript 类型 'string' 不可分配给类型

转载 作者:IT王子 更新时间:2023-10-29 02:46:46 27 4
gpt4 key购买 nike

这是我在 fruit.ts 中的内容

export type Fruit = "Orange" | "Apple" | "Banana"

现在我在另一个 typescript 文件中导入 fruit.ts。这是我的东西

myString:string = "Banana";

myFruit:Fruit = myString;

当我这样做

myFruit = myString;

我得到一个错误:

Type 'string' is not assignable to type '"Orange" | "Apple" | "Banana"'

如何将字符串分配给自定义类型 Fruit 的变量?

最佳答案

更新

如@Simon_Weaver 的回答所述,自 TypeScript 版本 3.4 以来,可以将其断言为 const:

let fruit = "Banana" as const;

旧答案

您需要 cast it :

export type Fruit = "Orange" | "Apple" | "Banana";
let myString: string = "Banana";

let myFruit: Fruit = myString as Fruit;

另请注意,在使用 string literals 时你只需要使用一个 |

关于javascript - typescript 类型 'string' 不可分配给类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37978528/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com