3

I want to check whether str is in Name

Is it possible?

/* imagination code */

type Name = 'a1' | 'a2' | .... | 'z100';

function isName(str: string): str is Name {
  switch (str) {
    case 'a1':
    case 'a2':
      // ...
    case 'z100':
      return true;
    default:
      return false;
  }
}

isName('alice') // -> true or false
pvcresin
  • 61
  • 1
  • 6
  • Possible duplicate of [Typescript: Check "typeof" against custom type](https://stackoverflow.com/questions/51528780/typescript-check-typeof-against-custom-type) – Hamza El Aoutar Oct 28 '19 at 12:27

1 Answers1

8

You can't go from a type to a runtime check. Types are erased at compile time so you can't really use any information in them at runtime. You can however go the other way, from a value go to a type:

const Name = ['a1', 'a2', 'z100'] as const // array with all values
type Name = typeof Name[number]; // extract the same type as before

function isName(str: string): str is Name {
  return Name.indexOf(str as any) !== -1; // simple check
}

isName('alice') // -> true or false

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357