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
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
To do this, you'll need to have something that lets you get the key of the interface at runtime. An interface does not exist at runtime - it's purely a TypeScript construct, so it doesn't exist in emitted code.
Make an array that contains the keys, declare it as const so it doesn't get automatically type-widened, and then you'll be able to turn it into the List type. Then you'll have both a type and a runtime array that you can use an .includes check on:
const listKeys = ['one', 'two'] as const;
type List = Record<typeof listKeys[number], string>;
// ...
const obj = {
one: 'one',
two: 'two',
three: 'three'
};
// Transformation to string[] needed because of an odd design decision:
// https://github.com/Microsoft/TypeScript/issues/26255
const newObj = Object.fromEntries(
Object.entries(obj).filter(
([key]) => (listKeys as unknown as string[]).includes(key)
)
);
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";