Home > OS >  Dynamic TypeScript key name
Dynamic TypeScript key name

Time:01-03

I am using TypeScript and i am wondering how can i "type" the following object.

{
    "code": 52,
    "somerandomstring123":"Some Data"
}

The thing is, that the KEY NAME somerandomstring123 is dynamically generated string and is not constant. So for example, the JSON could've been like this:

{
    "code": 52,
    "someOTHERstring456":"Some Data"
}

I tried using [key:string]: string like this:

interface SomeObjectData {
code: number;
[target: string]: string;
}

but it returns an error of: Property 'code' of type 'number' is not assignable to 'string' index type 'string'.

P.S.: The dynamic named property (e.g. somerandomstring123) value type is a string, so using string | number is not something i need.

CodePudding user response:

Try this:

type SomeObjectData = {
  [key: string]: string; // dynamic properties
} & {
  code: number; // static properties
};

CodePudding user response:

you can use the union type for the target.

interface SomeObjectData {
    [target: string]: string | number;
    code: number;
}

const data:SomeObjectData = { code: 12}
  • Related