简体   繁体   English

嵌套对象的打字稿限制

[英]Typescript restriction of nested objects

I have following general-purpose type definition: 我有以下通用类型定义:

export interface genericParameter {
    [k: string]: any
}

Is there a clever way to restrict such signature from assigning nested objects? 有什么聪明的方法来限制此类签名分配嵌套对象? For example I'd be happy to accept this type: 例如,我很乐意接受这种类型:

{
  prop1: 'val1',
  prop2: 123,
}

But not this: 但这不是:

{
  Obj1: {prop1: 'val1'},
  Obj2: {prop2: 123},
}

Thanks for any help! 谢谢你的帮助!

---EDIT--- - -编辑 - -

Considering following: 考虑以下内容:

[k: string]: string | number | /* unmanageable list */

Seems not an option I guess 我猜似乎没有选择

There is no way to tell typescript that can't be of a given type (not without done conditional types and a function anyway). 没有办法告诉打字稿不能是给定的类型(总之没有条件式和函数)。 In this case though, the list of primitive types is pretty short, so we can just enumerate the allowed types in a union 不过,在这种情况下,基本类型的列表很短,因此我们可以枚举联合中允许的类型

export interface genericParameter {
    [k: string]: number | string | boolean
}

Edit 编辑

As @tj-crowder points out, if you are going to use this type in many places, you might want to declare a type alias for the union (especially since what is a primitive may evolve over time with the addition of BigInt in the future) 正如@ tj-crowder指出的那样,如果要在许多地方使用此类型,则可能要声明联合的类型别名(尤其是因为将来随着BigInt的添加,原语可能会随着时间而发展)。 )

type primitive = number | string | boolean;
export interface genericParameter {
    [k: string]: primitive
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM