这是我的水果。ts
export type Fruit = "Orange" | "Apple" | "Banana"
现在我在进口水果。Ts在另一个typescript文件中。这是我有的
myString:string = "Banana";
myFruit:Fruit = myString;
当我这样做的时候
myFruit = myString;
我得到一个错误:
类型“string”不能赋值给类型“Orange”|“Apple”|
“香蕉”
如何将字符串分配给自定义类型水果的变量?
我也遇到了同样的问题,我做了以下修改,问题得到了解决。
打开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**;
以上所有答案都是有效的,然而,在某些情况下,字符串文字类型是另一个复杂类型的一部分。考虑下面的例子:
// in foo.ts
export type ToolbarTheme = {
size: 'large' | 'small',
};
// in bar.ts
import { ToolbarTheme } from './foo.ts';
function useToolbarTheme(theme: ToolbarTheme) {/* ... */}
// Here you will get the following error:
// Type 'string' is not assignable to type '"small" | "large"'.ts(2322)
['large', 'small'].forEach(size => (
useToolbarTheme({ size })
));
你有多种解决方案来解决这个问题。每个解决方案都是有效的,并且有自己的用例。
1)第一个解决方案是为size定义一个类型,并从foot .ts导出它。当您需要单独使用size参数时,这很好。例如,您有一个函数接受或返回类型大小的参数,而您想输入它。
// in foo.ts
export type ToolbarThemeSize = 'large' | 'small';
export type ToolbarTheme = {
size: ToolbarThemeSize
};
// in bar.ts
import { ToolbarTheme, ToolbarThemeSize } from './foo.ts';
function useToolbarTheme(theme: ToolbarTheme) {/* ... */}
function getToolbarSize(): ToolbarThemeSize {/* ... */}
['large', 'small'].forEach(size => (
useToolbarTheme({ size: size as ToolbarThemeSize })
));
2)第二个选项是将其转换为ToolbarTheme类型。在这种情况下,如果不需要,就不需要公开ToolbarTheme的内部。
// in foo.ts
export type ToolbarTheme = {
size: 'large' | 'small'
};
// in bar.ts
import { ToolbarTheme } from './foo.ts';
function useToolbarTheme(theme: ToolbarTheme) {/* ... */}
['large', 'small'].forEach(size => (
useToolbarTheme({ size } as ToolbarTheme)
));
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来表示一个必须为真或假的布尔值。这在有歧视的工会中有时是有用的。你一看到就知道了。