Typescript 型 'string' は型に割り当てることができません 質問する

Typescript 型 'string' は型に割り当てることができません 質問する

fruit.ts に載っているものはこちら

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

今、別のTypeScriptファイルにfruit.tsをインポートしています。これが私の持っているものです

myString:string = "Banana";

myFruit:Fruit = myString;

私がする時

myFruit = myString;

エラーが発生します:

タイプ 'string' はタイプ '"Orange" | "Apple" | "Banana"' に割り当てることはできません

カスタム タイプ Fruit の変数に文字列を割り当てるにはどうすればよいですか?

ベストアンサー1

アップデート

@Simon_Weaver の回答で述べたように、TypeScript バージョン 3.4 以降では、次のようにアサートすることが可能ですconst

let fruit = "Banana" as const;

古い回答

必要になりますそれをキャストする:

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

let myFruit: Fruit = myString as Fruit;

また、使用時には文字列リテラル1つだけ使用する必要があります|

おすすめ記事