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?
In the first example, you're just defining the type of indexes, you're not specify the indexes as you might by using in:
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.