具有一些已知和一些未知属性名称的对象的 Typescript 接口 [英] Typescript interface for objects with some known and some unknown property names

查看:23
本文介绍了具有一些已知和一些未知属性名称的对象的 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'},
    ...
    ...
};

在这个对象中,fixedKey1fixedKey2 是该对象中的已知键.unknownKey - 值对可以从 1-n 变化.

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

但这会引发以下错误:

类型编号的变量不可分配给类型对象

Variable of type number is not assignable of type object

我发现它无法将此接口分配给fixedKey - value"对.

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?

推荐答案

这不是你想要的,但你可以使用 联合类型:

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

这篇关于具有一些已知和一些未知属性名称的对象的 Typescript 接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆