Why does index signature of the object type accept an object with no properties?

692 Views Asked by At

I have a Dictionary interface where I want to have index type as string and values to be of string type.

interface One {
 [key: string]: string;
}

If I annotated this type to a constant variable that holds an object with no properties, then it doesn't give me an error.

const example: One = {}; // no error why?

Another question with the above approach is that const example = {} as One; this also works.

If I don't provide the index signature of the object then it gives me an error that you have missing properties.

interface Two {
 first: string;
 second: string;
}

const example2: Two: {}; // error missing properties
// to tackle this situation I used type assertion

const example3 = {} as Two; // no error

My question is why does the example variable accept an object with no properties?

You may have a question that why I want to have an object with no properties. The reason is I want to add some properties to that empty object later. In that case, should I do type assertion or type annotation?

1

There are 1 best solutions below

0
On

In the first example, you're just defining the type of indexes, you're not specify the indexes as you might by using in:

type Keys = 'first' | 'second'
type One = { [P in Keys]: string };

const one: One = {}; // Error: Type '{}' is missing the following properties from type 'One': first, second

In the second example you're asserting that the value is Two. You're telling typescript to trust you. If you want to use the Two type but make the fields optional, you can use the Partial utility type.

const example2: Partial<Two> = {}; // valid
const example3: Partial<Two> = { first: '1' }; // valid
const example3: Partial<Two> = { third: '3' }; // Error: Object literal may only specify known properties.