Jeff
Jeff

Reputation: 1879

TypeScript: Type Guard for custom type

Goal: Trying to create a type guard for a custom type.

Here is my custom type:

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

This is my first attempt in creating type guard, but this seems redundant in declaring allowed values twice:

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

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

Is there a better way of doing a type guard for custom literal types?

Thank you

Upvotes: 2

Views: 540

Answers (1)

Zze
Zze

Reputation: 18805

The reason you are getting that error is because:

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.

I had to look this up.... the example I found was 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): unknownString is AppProviders {
  return (APP_PROVIDERS as unknown as string[]).includes(unknownString);
}

Upvotes: 4

Related Questions