Home > Blockchain >  TypeScript check string match type
TypeScript check string match type

Time:10-29

I have something like this:

type UnionType = 'one' | 'two' | 'three'

const myNumber: string = 'just a string'

// function to check if myNumber match UnitionType

Is there any way to do that? because I don't want to write:

['one', 'two', 'three'].includes(myNumber)

CodePudding user response:

I would change type into an enum, then you can easily make an comparison with your string with the keyword in.

enum UnionEnum {
    'one',
    'two',
    'three'
}

const myNumber: string = 'just a string';

// function to check if myNumber match UnitionType

console.log(myNumber in UnionEnum); // Result -> false
  • Related