TypeScript类型检查器似乎接受以下代码。为什么会这样?我可以以某种方式使它更严格吗?
const foo: {} = {bar: 123}
const foo: { [index: string]: never } = {} // no error
const bar: {[index : string]: never } = {a:1} // error
任何对象都可以作为{}的符号。但通常情况下,当你尝试使用它后,你将没有来自类型的属性。
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
我解决了这个问题,将类型定义为 Record<any, never>
.
const foo: Record<any,never> = {} // this works
const bar: Record<any,never> = {bar: 123} // this creates error as expected