这是我的水果。ts

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

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

myString:string = "Banana";

myFruit:Fruit = myString;

当我这样做的时候

myFruit = myString;

我得到一个错误:

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

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


当前回答

这个问题被标记为Angular,尽管它实际上与Angular没有任何关系。然而,有(至少)一个Angular特定的情况,你可能会意外地得到这个错误。

如果你禁用了strictNullInputTypes 如果你使用一个文字类型,比如Fruit作为@Input() 你试图将'Orange'传递给一个输入,它被解释为一个字符串。

这将在Angular 13.1中修复。

https://github.com/angular/angular/pull/38305

其他回答

我也遇到了同样的问题,我做了以下修改,问题得到了解决。

打开watchQueryOptions.d.ts文件

\apollo-client\core\watchQueryOptions.d.ts

将查询类型更改为any而不是DocumentNode,与突变相同

之前:

export interface QueryBaseOptions<TVariables = OperationVariables> {
    query: **DocumentNode**;

后:

export interface QueryBaseOptions<TVariables = OperationVariables> {
    query: **any**;

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

例子:

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

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

示例模型:

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';
}

这个问题被标记为Angular,尽管它实际上与Angular没有任何关系。然而,有(至少)一个Angular特定的情况,你可能会意外地得到这个错误。

如果你禁用了strictNullInputTypes 如果你使用一个文字类型,比如Fruit作为@Input() 你试图将'Orange'传递给一个输入,它被解释为一个字符串。

这将在Angular 13.1中修复。

https://github.com/angular/angular/pull/38305

Typescript 3.4引入了新的'const'断言

您现在可以防止文字类型(例如。'橙色'或'红色')被“拓宽”为使用所谓的const断言的类型字符串。

你将能够做到:

let fruit = 'orange' as const;  // or...
let fruit = <const> 'orange';

然后它就不会再变成字符串了,这就是问题的根源。

你也可以在整个对象上这样做:

let animals = [ { species: 'dog' }, { species: 'cat' } ] as const;

type firstAnimal = (typeof animals)[0]['species'];  // string literal 'dog'

额外提示:你也可以使用<const> false或<const> true来表示一个必须为真或假的布尔值。这在有歧视的工会中有时是有用的。你一看到就知道了。