【问题标题】:use object key as key for another object使用对象键作为另一个对象的键
【发布时间】:2022-01-25 16:57:55
【问题描述】:
我想在 TypeScript 中创建一个类型并使用另一个对象的值作为它的键
const routes = {
home: "HOME",
profile: "PROFILE"
}
export type NavigatorParamList = {
[routes.home]: undefined;
[routes.profile]: undefined;
};
我知道这段代码不起作用!
知道怎么做吗?
【问题讨论】:
标签:
javascript
typescript
【解决方案1】:
您的对象的属性是可变字符串,TypeScript 不允许您将它们用作类型的计算属性,除非您使用 as const 将它们设为只读文字。
const routes = {
home: "HOME",
profile: "PROFILE"
} as const;
【解决方案2】:
这就是String enums 的用途:
TS Playground
enum Route {
Home = "HOME",
Profile = "PROFILE"
}
// using a union of individual enum members:
type NavigatorParamList1 = Record<Route.Home | Route.Profile, undefined>; // { HOME: undefined; PROFILE: undefined; }
// or if you want to use all enum members:
type NavigatorParamList2 = Record<Route, undefined>; // { HOME: undefined; PROFILE: undefined; }
// or independently-defined members
type NavigatorParamList3 = {
[Route.Home]: undefined;
[Route.Profile]: undefined;
}
【解决方案3】:
它适用于映射类型和新的as 子句:
const routes = {
home: "HOME",
profile: "PROFILE"
} as const;
type AcceptableKeyTypes = string | number | symbol;
type ObjectWithValuesWhichCanBeKeys = {[key: AcceptableKeyTypes]: AcceptableKeyTypes};
type ValuesAsKeys<T extends ObjectWithValuesWhichCanBeKeys> = {[P in keyof T as T[P]]: unknown};
let test: ValuesAsKeys<typeof routes> = {HOME: 7, PROFILE: 4};
TypeScript playground
我在这里使用的是泛型类型:ValuesAsKeys<T>。
需要将 T 的值限制为可接受作为键的类型:字符串 |号码 |符号。
[P in keyof T] 部分是一个映射类型,它遍历 T 的所有键。然后,as 子句将键映射到一个新值,在本例中为 T[P],这是当前的迭代键。
最后,值是未知的,所以你可以使用任何你想要的新值。在我给出的示例中,我使用数字作为新值,但它可以是任何值。
请注意,正如其他答案中所说,routes 需要具有as const 断言,以便将字符串值视为文字类型,然后可以用作类型键。