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

后端 未结 3 1057
庸人自扰
庸人自扰 2020-12-08 09:32

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\": \"some         


        
相关标签:
3条回答
  • 2020-12-08 09:53

    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;
    }
    
    0 讨论(0)
  • 2020-12-08 10:10

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

    interface IfcObject {
        [key: string]: string | {
            param1: number[];
            param2: string; 
            param3: string;
        }
    }
    
    0 讨论(0)
  • 2020-12-08 10:15

    The correct answer to this question is:

    export interface IfcObjectValues {
        param1: number[];
        param2: string;
        param3: string;        
    }
    
    interface MyInterface {
      fixedKey1: string,
      fixedKey2: number,
      [x: string]: IfcObjectValues, 
    }
    

    Your code in action, see here.

    0 讨论(0)
提交回复
热议问题