You can use a mapped type in TypeScript to extract the keys of an interface as an array of strings at compile-time. Here's an example:
index.ts177 chars10 lines
In this example, we define an interface MyInterface
with two properties foo
and bar
. We then define a mapped type MyArray
that uses the keyof
operator to extract the keys of MyInterface
as an array of strings.
You can then use the MyArray
type to define variables or parameters that accept an array of keys corresponding to an interface. For example:
index.ts213 chars7 lines
In this example, we define a function myFunction
that takes an array of strings corresponding to the keys of MyInterface
. We can call myFunction
with an array containing the correct keys, but not with an array that contains an unknown key. Thanks to TypeScript's type checking, we get a compile-time error if we try to call myFunction
with an invalid array.
gistlibby LogSnag