ChatGPT解决这个技术问题 Extra ChatGPT

具有一些已知和一些未知属性名称的对象的 Typescript 接口

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?


P
Paleo

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.


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

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

Your code in action, see here.


Property 'fixedKey2' of type 'number' is not assignable to string index type 'IfcObjectValues'. This occurs in TypeScript 2.8.3.
This won't work, unless you type the unknown properties as any
This won't work, unless you type the unknown properties as unknown
This is not a correct answer, and the linked playground does not reflect the code posted here.
P
Pang

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