Home > Net >  An object cannot have key attribute
An object cannot have key attribute

Time:06-01

I need an object type that cannot have the attribute key.But other attributes can be owned.

const obj: ??? = {key:1, value: 1} // error:Cannot have the attribute key
const obj: ??? = {other1:1,other2:2} // OK

CodePudding user response:

Try this:

type CanNotHaveKey = { [key: string]: any } & {
    key?: never
}

const obj: CanNotHaveKey = { key: 1, value: 1 } // ❌ Type 'number' is not assignable to type 'undefined'.
const objTwo: CanNotHaveKey = { other1: 1, nice: { good: "string" }, other2: 2 } // ✔ 

TS Playground

My idea behind it is to combine the types any and key, where key is a type which never occurs.

Read more about never: https://www.typescriptlang.org/docs/handbook/basic-types.html#never

  • Related