对象不能有键属性
An object cannot have key attribute
我需要一个对象类型不能拥有属性key.But其他属性可以拥有。
const obj: ??? = {key:1, value: 1} // error:Cannot have the attribute key
const obj: ??? = {other1:1,other2:2} // OK
试试这个:
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 } // ✔
我的想法是结合类型 any
和 key
,其中 key
是一种永远不会出现的类型。
阅读更多关于从不的内容:https://www.typescriptlang.org/docs/handbook/basic-types.html#never
我需要一个对象类型不能拥有属性key.But其他属性可以拥有。
const obj: ??? = {key:1, value: 1} // error:Cannot have the attribute key
const obj: ??? = {other1:1,other2:2} // OK
试试这个:
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 } // ✔
我的想法是结合类型 any
和 key
,其中 key
是一种永远不会出现的类型。
阅读更多关于从不的内容:https://www.typescriptlang.org/docs/handbook/basic-types.html#never