简体   繁体   中英

Typescript not nested object type

I want to declare generic object type that is not nested (value is not object/array, only primitive )

For example:

Valid:

{
 a:"value",
 b:false,
 c:4
}

Invalid:

{
a:{b:"c"}
}

{
a:[5]
}

Something like this (of course it's invalid declaration):

interface NotNestedObject  {
  [x: any]: not Array/Object;
}

Luckily there aren't many primitive types in typescript, so you can just simply list them all in a union type.

interface NotNestedObject  {
    [x: string]: number|boolean|string|null|undefined;
}

if you want dates to be included

interface NotNestedObject  {
    [x: string]: number|boolean|string|Date|null|undefined;
}

if you want functions also to be included

interface NotNestedObject  {
    [x: string]: number|boolean|string|Date|Function|null|undefined;
}

And of course you can remove null and undefined if you don't want them to be allowed. They are included by default unless you enable strictNullChecks compiler option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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