Typescript interface for objects with some known and some unknown property names

Typescript

Typescript Problem Overview


I have an object where all the keys are string, some of the values are string and the rest are objects in this form:

var object = {
    "fixedKey1": "something1",
    "fixedKey2": "something2",
    "unknownKey1": { 'param1': [1,2,3], 'param2': "some2", 'param3': 'some3'},
    "unknownKey2": { 'param1': [1,2,3], 'param2': "some2", 'param3': 'some3'},
    "unknownKey3": { 'param1': [1,2,3], 'param2': "some2", 'param3': 'some3'},
    ...
    ...
};

In this object fixedKey1 and fixedKey2 are the known keys which will be there in that object. unknownKey - value pair can vary from 1-n.

I tried defining the interface of the object as:

interface IfcObject {
    [keys: string]: {
        param1: number[];
        param2: string; 
        param3: string;
  }
}

But this throws the following error:

> Variable of type number is not assignable of type object

Which I found out that it is not able to assign this interface to "fixedKey - value" pair.

So, how can I do the type checking of this kind of variables?

Typescript Solutions


Solution 1 - Typescript

It's not exactly what you want, but you can use a union type:

interface IfcObject {
    fixedKey1: string
    fixedKey2: string
    [key: string]: string | {
        param1: number[];
        param2: string; 
        param3: string;
    }
}

It covers your case. But the unknown properties could be of type string.

Solution 2 - Typescript

export interface IfcObjectValues {
    param1: number[];
    param2: string;
    param3: string;        
}

interface MyInterface {
  fixedKey1: string,
  fixedKey2: number,
  [x: string]: IfcObjectValues, 
}

Your code in action, see here.

Solution 3 - Typescript

As @Paleo explained, you can use union property to define an interface for your corresponding object.

I would say you should define an interface for object values and then you should define your original object.

Sample interface can be:

export interface IfcObjectValues {
    param1: number[];
    param2: string;
    param3: string;        
}

export interface IfcMainObject {
 [key : string]: string | IfcObjectValues;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionyugantar kumarView Question on Stackoverflow
Solution 1 - TypescriptPaleoView Answer on Stackoverflow
Solution 2 - TypescriptberslingView Answer on Stackoverflow
Solution 3 - TypescriptAjayView Answer on Stackoverflow