dannyxnda
dannyxnda

Reputation: 1014

TypeScript check string match type

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)

Upvotes: 1

Views: 1122

Answers (1)

Blazorman
Blazorman

Reputation: 164

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

Upvotes: 1

Related Questions