在TypeScript中如何防止属性被添加到一个空对象中?

问题描述 投票:1回答:3

TypeScript类型检查器似乎接受以下代码。为什么会这样?我可以以某种方式使它更严格吗?

const foo: {} = {bar: 123}
typescript
3个回答
1
投票
const foo: { [index: string]: never } = {} // no error
const bar: {[index : string]: never } = {a:1} // error

游乐场


0
投票

任何对象都可以作为{}的符号。但通常情况下,当你尝试使用它后,你将没有来自类型的属性。

const foo: {} = {bar: 123}
foo.bar // error : Property 'bar' does not exist on type '{}'

你应该先定义一个类型,或者在你的声明中推断类型。

// with a type (an interface would also work)
type Foo = {
    bar: number;
}

const foo: Foo = {bar: 123};
foo.bar // type: number

// with inference :
const foo = {bar: 123};
foo.bar // type: number

0
投票

类型 对象 类型是相当广泛的。它既可以是空的,也可以是有属性的,这是完全有效的。

我建议使用 无效 类型代替空对象,如果您希望验证对象属性,则用类型或接口代替。

请看 TypeScript游乐场

interface Foo {
    bar: number
}

var foo: Foo | null = null

foo = {
    bar: 123
}

-1
投票

我解决了这个问题,将类型定义为 Record<any, never>.

const foo: Record<any,never> = {} // this works
const bar: Record<any,never> = {bar: 123} // this creates error as expected
© www.soinside.com 2019 - 2024. All rights reserved.