how to get an array of strings from an interface in compile time in typescript

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.ts
interface MyInterface {
  foo: number;
  bar: string;
}

type MyArray = Array<keyof MyInterface>;

// The `MyArray` type will be equivalent to:
// type MyArray = ["foo", "bar"]
177 chars
10 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.ts
function myFunction(keys: MyArray) {
  // ...
}

myFunction(["foo", "bar"]); // OK
myFunction(["foo", "baz"]); // Type error: Argument of type 'string[]' is not assignable to parameter of type '("foo" | "bar")[]'
213 chars
7 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