Type comparison with String

Viewed 53

Is this possible or is there an easy way to solve this ?

I would like to compare a string value with a type. I have a type like below and a string value incoming from api request.

type stringTypes = 'abc' | 'asd'

const testVal = 'testVal'

if (testVal !== stringTypes) {
  // throw error
}

I have solved like below but I wondered if there' s another options.

type stringTypes = 'abc' | 'asd'

const testVal = 'testVal'

const controlArr: stringTypes[] = ['asd', 'abc']

if (!controlArr.includes(testVal)) {
  // throw error
}

EDIT1: I can use Enums but in typescript enums are not extendable. In my case, I need to extend the types according to the db model as shown below. So I need to do comparison with string and a type.

type stringTypes = 'abc' | 'asd'
type channelTypes = stringTypes | 'foo' | 'bar'
type streamTypes = stringTypes | 'das' | 'xyz'

const testVal = 'testVal'

if (testVal !== stringTypes) {
  // throw error
}
1 Answers

TypeScript is just a compiler, so you can't iterate thought a type, but you could achieve what you want by using enum type

const testVal = 'testVal'

enum stringTypes {
  'Abc' = 'abc',
  'Dsd' = 'asd',
}

//Check if string is enum value
const isEnumValue = (value: string, enumType: any) => {
  return Object.values(enumType).includes(value)
}

console.log(isEnumValue('abc', stringTypes)) //true
Related