Reputation: 973
TypeScript type checker seems to accept the following code. Why is that? Can I somehow make it more strict?
const foo: {} = {bar: 123}
Upvotes: 1
Views: 650
Reputation: 2747
const foo: { [index: string]: never } = {} // no error
const bar: {[index : string]: never } = {a:1} // error
Upvotes: 1
Reputation: 973
I solved the problem by defining the type as Record<any, never>
.
const foo: Record<any,never> = {} // this works
const bar: Record<any,never> = {bar: 123} // this creates error as expected
Upvotes: 2
Reputation: 7260
The object type is pretty broad. It’s perfectly valid for it to be either empty or have properties.
I would recommend using the null type instead of an empty object and a type or interface if you wish to validate object properties.
interface Foo {
bar: number
}
var foo: Foo | null = null
foo = {
bar: 123
}
Upvotes: 1
Reputation: 1159
any object is asignable to {}. But often, when you try to use it after you will not have the properties from the type :
const foo: {} = {bar: 123}
foo.bar // error : Property 'bar' does not exist on type '{}'
You should define a type first, or infer the type on your declaration :
// 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
Upvotes: 0