这是我的水果。ts

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

现在我在进口水果。Ts在另一个typescript文件中。这是我有的

myString:string = "Banana";

myFruit:Fruit = myString;

当我这样做的时候

myFruit = myString;

我得到一个错误:

类型“string”不能赋值给类型“Orange”|“Apple”| “香蕉”

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


当前回答

例如,如果在模拟数据时转换为下拉值[],则将其组合为具有value和display属性的对象数组。

例子:

[{'value': 'test1', 'display1': 'test display'},{'value': 'test2', 'display': 'test display2'},]

其他回答

更新

正如@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;

还要注意,当使用字符串字面量时,您只需要使用一个|

我知道这有点过时了,但这里可能有更好的解决方案。

当需要字符串,但希望字符串只匹配某些值时,可以使用enum。

例如:

enum Fruit {
    Orange = "Orange",
    Apple  = "Apple",
    Banana = "Banana"
}

let myFruit: Fruit = Fruit.Banana;

现在您将知道,无论如何,myFruit将始终是字符串“Banana”(或您选择的任何其他可枚举值)。这对很多事情都很有用,无论是将类似的值分组,还是将用户友好的值映射到机器友好的值,同时强制和限制编译器允许的值。

在扩散的数组中,这个错误仍然会被抛出:

export type Fruit = "Orange" | "Apple" | "Banana"
export type FruitArray = Fruit[];

const someFruits= ["Banana"];

const workingFruits: FruitArray = ["Orange", "Apple"]; // Works

// Even orange and apple show: Type 'string' is not assignable to type Fruit
const brokenAllFruits: FruitArray = [...someFruits, "Orange", "Apple"]; 

// As const is needed in the spread array
const someConstFruits= ["Banana" as const];
const workingAllFruits: FruitArray = [...someConstFruits, "Orange", "Apple"]; // Works

如果你正在与类一起工作,你可以做以下其中之一:

示例模型:

type Fruit = 'Apple' | 'Banana';

interface ClassWithFruit  {
  fruit: Fruit;
}

实现模型的类,这里有三个选项:

class MyClass implements ClassWithFruit {
  // option 1
  fruit = 'Apple' as const;

  // option 2
  fruit = <const>'Apple';
  
  // option 3
  readonly fruit = 'Apple';
}

当传递道具到React组件时,我也遇到了类似的问题。

原因:我在myArray上的类型推断没有正确工作

https://codesandbox.io/s/type-string-issue-fixed-z9jth?file=/src/App.tsx

特别感谢Reactiflux的Brady在这个问题上的帮助。