Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Check If A String Exists as An Interface Key

Can I check if a string exists as an interface key

interface list {
    one: string
    two: string
}

const myNumber = "one"

How do I check if myNumber value is an interface key

like image 968
succeed Avatar asked Feb 27 '26 17:02

succeed


1 Answers

The type of Typescript is not a value.

Therefore, operation of Javascript is impossible.

However, in the example, the type can be set so that myNumber is the type corresponding to the key.

interface list {
    one: string
    two: string
}

const myNumber: keyof list = "one"; // myNumber allow only "one" or "two";
like image 133
hyundeock Avatar answered Mar 01 '26 12:03

hyundeock