How to correctly get all properties of a specific key type from an interface in TypeScript?

  Kiến thức lập trình

When working with arrays, the following is valid:

const MyArray = [
  { name: "Alice", age: 15 },
  { name: "Bob", age: 23 },
  { name: "Eve", age: 38 },
];
 
type Person = typeof MyArray[number];

Then I tried the same idea with interfaces:

interface A {
  a: number;
}

type KeysOfA = typeof A[string]

but got an error:

'A' only refers to a type, but is being used as a value here.

If I remove the typeof here, I get another error:

Type 'A' has no matching index signature for type 'string'.

Given that I want to get all the properties of the key type string, what should I do?

2

The typeof operator works on values that exist at runtime but interfaces are only type-level constructs and do not exist at runtime.

LEAVE A COMMENT