如何在TypeScript跨文件场景下定义基于动态变量的类型?
解决方案
方法一:从App.tsx导出data.games的类型
把data.games的类型从业务文件导出,再在类型文件中导入使用:
App.tsx
const data = { games: { type: [], sport: [], category: [] } }; // 导出data.games的类型 export type GamesType = typeof data.games;
Apptype.ts
import { GamesType } from './App'; export type Valid = keyof GamesType; export interface IOption { id: number; value: string; valid: Record<Valid, number[]>; }
方法二:提前定义GamesType并双向约束
如果data是动态获取的(比如接口返回),可以先在类型文件里定义好结构,再用它约束业务文件中的data:
Apptype.ts
// 先定义games的结构类型 export type GamesType = { type: any[]; sport: any[]; category: any[]; }; export type Valid = keyof GamesType; export interface IOption { id: number; value: string; valid: Record<Valid, number[]>; }
App.tsx
import { GamesType } from './Apptype'; // 用类型约束data,确保结构符合要求 const data: { games: GamesType } = { games: { type: [], sport: [], category: [] } };
方法三:导出data常量(仅适用于固定数据)
如果data是固定不变的常量,可以直接导出它,在类型文件中导入后获取类型:
App.tsx
// 导出data常量 export const data = { games: { type: [], sport: [], category: [] } };
Apptype.ts
import { data } from './App'; export type Valid = keyof typeof data.games; export interface IOption { id: number; value: string; valid: Record<Valid, number[]>; }
内容的提问来源于stack exchange,提问作者Hello World
相关产品推荐
相关产品推荐

