javascript - 如何在 TypeScript 中添加动态变量名?
我有两个文件,
App.tsx:
const data = {games:{type: [], sport: [], category: []}}
以上是我收到的动态数据。
我需要将上述 keyof typeof data.games 设置为有效类型,如
type Valid = keyof typeof data.games
如果是同一个文件,那么像上面那样分配就没有问题。
但是我有单独类型的文件,比如,
Apptype.ts
// How can I make the below keyof typeof [dynamicName] ?
export type Valid = keyof typeof data.games;
export interface IOption {
id: number;
value: string;
valid: Record<Valid, number[]>;
}
在上述文件中,data.games 会报错,因为该文件中不会有这样的变量名。
那么我如何将动态值分配给 keyof typeof [.....]?
工作示例:
答案#1
你可以从 App.tsx 导出和导入数据。并使用 Apptype.ts 导入类型
App.tsx:
import type { IOption, IState } from "./Apptype";
// ...
Apptype.tsimport { data } from "./App";
export interface IState {
[key: string]: number;
}
export type Valid = keyof typeof data.games;
export interface IOption {
id: number;
value: string;
valid: Record<Valid, number[]>;
}
代码沙箱