Typescript类型'string'不能分配给类型 [英] Typescript Type 'string' is not assignable to type

查看:8229
本文介绍了Typescript类型'string'不能分配给类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我在fruit.ts中的含义。

Here's what I have in fruit.ts

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

现在我在另一个打字稿文件中导入fruit.ts.这就是我拥有的东西

Now I'm importing fruit.ts in another typescript file. Here's what I have

myString:string = "Banana";

myFruit:Fruit = myString;

当我这样做时

myFruit = myString;

我收到错误消息:


类型'字符串'不能分配给类型'Orange| Apple|
Banana'

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

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

How can I assign a string to a variable of custom type Fruit?

推荐答案

你需要强制转换

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

let myFruit: Fruit = myString as Fruit;

还要注意使用字符串文字您只需要使用一个 |

Also notice that when using string literals you need to use only one |

这篇关于Typescript类型'string'不能分配给类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆