如何从 TypeScript 的接口中正确获取特定键类型的所有属性?

问题描述 投票:0回答:1

使用数组时,以下内容有效:

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

然后我在界面上尝试了同样的想法:

interface A {
  a: number;
}

type KeysOfA = typeof A[string]

但出现错误:

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

如果我删除这里的

typeof
,我会收到另一个错误:

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

鉴于我想获取密钥类型的所有属性

string
,我该怎么办?

typescript
1个回答
0
投票

typeof
运算符适用于运行时存在的值,但接口只是类型级别的构造,在运行时不存在。

© www.soinside.com 2019 - 2024. All rights reserved.