【问题标题】:TypeScript: Type Guard for custom typeTypeScript:自定义类型的类型保护
【发布时间】:2020-11-11 07:49:49
【问题描述】:

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

这是我的自定义类型:

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

有没有更好的方法来为自定义文字类型做类型保护?

谢谢

【问题讨论】:

    标签: typescript typeguards


    【解决方案1】:

    您收到该错误的原因是:

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

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

    我必须查一下......我找到的例子是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);
    }
    

    【讨论】:

    • +1 我偏爱(APP_PROVIDERS as string[]).includes(key),因为它更能表达你在做什么(key 可能不是AppProviders,但APP_PROVIDERS 的元素肯定都是@ 987654329@s),但一般方法是我推荐的方法
    猜你喜欢
    • 2021-01-22
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 2020-02-01
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多