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

TypeScript: Type Guard for custom type

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

这是我的自定义类型:

type AppProviders =  'box' | 'dropbox' | 'google';

这是我第一次尝试创建 type guard,但这在两次声明允许值方面似乎是多余的:

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

function isAppProviders(provider): provider is AppProviders {
    return appProviders.includes(provider)
}

是否有更好的方法来为自定义文字类型执行类型保护?

谢谢

您收到该错误的原因是:

https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-aliases

type Easing = "ease-in" | "ease-out" | "ease-in-out";
String literal types allow you to specify the exact value a string must have. In practice string literal types combine nicely with union types, type guards, and type aliases. You can use these features together to get enum-like behavior with strings.

我不得不查一下....我找到的例子是 https://www.damirscorner.com/blog/posts/20200619-StringLiteralTypeGuardInTypescript.html

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