cyberixae
cyberixae

Reputation: 973

How do I prevent properties from being added to an empty object in TypeScript?

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

Answers (4)

Acid Coder
Acid Coder

Reputation: 2747

const foo: { [index: string]: never } = {} // no error
const bar: {[index : string]: never } = {a:1} // error

playground

Upvotes: 1

cyberixae
cyberixae

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

sunknudsen
sunknudsen

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.

See TypeScript playground

interface Foo {
    bar: number
}

var foo: Foo | null = null

foo = {
    bar: 123
}

Upvotes: 1

JeromeBu
JeromeBu

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

Related Questions