Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define an interface for objects with dynamic keys?

Tags:

typescript

People also ask

How do you define type of key in an object?

Use the keyof typeof syntax to create a type from an object's keys, e.g. type Keys = keyof typeof person . The keyof typeof syntax returns a type that represents all of the object's keys as strings. index.ts.

How do you define a object in TypeScript?

Syntax. var object_name = { key1: “value1”, //scalar value key2: “value”, key3: function() { //functions }, key4:[“content1”, “content2”] //collection }; As shown above, an object can contain scalar values, functions and structures like arrays and tuples.

What is Interface key and value object?

When we define an object with properties (keys) and values, TypeScript creates an implicit interface by looking at the property names and data type of their values in the object. This happens because of the type inference.

What is a dynamic key?

Dynamic keys are one-time symmetric cryptographic keys. forming a sequence of keys. Similar in nature to one- time pad, every message in the system is encrypted by a. different cryptographic key.


Your object looks like a dictionary of Object arrays

interface Dic {
    [key: string]: Object[]
}

The typescript literature often refers to this pattern as "the description of an indexable object" with a general form

interface Dic {
    [key: string|number]: object_type
}

or

type Dic = {
    [key: string|number]: object_type
}

There's now a dedicated Record type in TypeScript:

const myObject: Record<string, object[]> = { ... }

Also, consider typing the keys whenever possible:

type MyKey = 'key1' | 'key2' | ...

const myObject: Record<MyKey, object[]> = { ... }

{ [x: string]: T }

and

Record<string, T>

usually will serve for all your objectives. However, I got to a strange point where after some type operations the first option was returning to me both [x: string] and [x: number], and I wasn't being able to use the Record, as it was a recursive type operation and Typescript was throwing an error saying my recursive type wasn't generic.

So, studying the really small Record code, I came to this solution that solved my complex problem:

{ [P in string]: T }

Edit: I also usually have this in every Typescript code I write, in a utils.ts file:

export type obj<T = unknown> = Record<string, T>

Faster and cleaner than using the Record all the time.

E.g.:

type MyObjectType = {
  propA: obj; // An object with unknown props
  propB: obj<number>; // An object with number props
}

don't know about interface, for dynamic objects we can go something like this:

let memoTable: { [k: number]: number } = {};
memoTable[1]=5;
memoTable[2]=7;

I would suggest a solution with Map, maybe for someone it will be useful:

type TKey = 'key1' | 'key2' | 'key3';
type TValue = object[];

type TMapper = Map<TKey, TValue>; // But also you can use Record instead of Map