Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/437.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
TypeScript:自定义类型的类型保护_Typescript_Typeguards - Fatal编程技术网

TypeScript:自定义类型的类型保护

TypeScript:自定义类型的类型保护,typescript,typeguards,Typescript,Typeguards,目标:尝试为自定义类型创建类型保护。 这是我的自定义类型: type AppProviders = 'box' | 'dropbox' | 'google'; 这是我第一次尝试创建,但两次声明允许的值似乎是多余的: type AppProviders = 'box' | 'dropbox' | 'google'; const appProviders: AppProviders[] = [ 'box', 'dropbox', 'google' ]; function isAppProvi

目标:尝试为自定义类型创建类型保护。

这是我的自定义类型:

type AppProviders =  'box' | 'dropbox' | 'google';
这是我第一次尝试创建,但两次声明允许的值似乎是多余的:

type AppProviders =  'box' | 'dropbox' | 'google';
const appProviders: AppProviders[] = [ 'box', 'dropbox', 'google' ];

function isAppProviders(provider): provider is AppProviders {
    return appProviders.includes(provider)
}
有没有更好的方法为自定义文字类型执行类型保护


谢谢

您出现此错误的原因是:

type Easing=“ease-in”|“ease-out”|“ease-in-out”
字符串文字类型允许您指定字符串必须具有的确切值。实际上,字符串文字类型与联合类型、类型保护和类型别名很好地结合在一起。您可以将这些功能结合使用,以获得类似枚举的字符串行为

我得查一下。。。。我发现的例子是

+1我偏爱
(APP\u PROVIDERS作为string[])。包括(key)
,因为它更能表达你正在做的事情(
key
可能不是
AppProviders
,但
APP\u PROVIDERS
的元素肯定都是
string
s),但我推荐的是一般方法
export const APP_PROVIDERS = ['a', 'b'] as const;
export type AppProviders = typeof APP_Providers[number];

export function isAppProviders(unknownString: string): key is AppProviders {
  return (APP_PROVIDERS as string[]).includes(unknownString as AppProviders);
}