Home > Net >  How to add dynamic variable name in typescript?
How to add dynamic variable name in typescript?

Time:11-29

I am having two files,

App.tsx:

const data = {games:{type: [], sport: [], category: []}}

The above is the dynamic data I receive .

I am in the need to set the above keyof typeof data.games to the type valid like,

type Valid = keyof typeof data.games

If it is same file then no issues to assign like the above.

But I have type file separately like,

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[]>;
}

In the above file data.games throw error because there will not be such variable name in this file.

So how can I assign the dynamic value to keyof typeof [.....]?

Working Example:

Edit disable-dependent-dropdown-option-in-reactjs (forked)

CodePudding user response:

You can export and import the data from the App.tsx. And import types from Apptype.ts using

App.tsx:

import type { IOption, IState } from "./Apptype";
// ...

Apptype.ts

import { 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[]>;
}

codesandbox

  • Related