Why Indexed access types don’t work with interfaces 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'.

Why Indexed access types don’t work with interfaces in TypeScript?

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'.

LEAVE A COMMENT