Creating object based on interface type in Typescript
Interface in Typescript is used to tell the compiler what the shape of the JS object should look like.
It is a compile time construct hence it will not have generated code as type checking in Typescript is only done at compile time rather than runtime.
I'm learning Typescript and found different ways to create an object which conforms to the interface type but not all might have the type safe guarantee as you expect.
Let's take the following interface
interface Foo {
bar: string;
qux: number;
}
You can create an object as following
Method 1
const waldo = <Foo> {
bar: "Hello",
qux: 7
}
Method 2
const waldo: Foo = {
bar: "Hello",
qux: 7
}
Both of these methods will work. The issue arises when you try adding or removing properties from the interface Foo
.
If we add another property as following
interface Foo {
bar: string;
qux: number;
baz: boolean;
}
After adding baz
property you might think that compiler should throw error wherever Foo
instance is being created letting you know there is a missing property.
That is not the case. If you created object using Method 2 then it will throw compile error but Method 1 will not throw any error and only at runtime you will get baz
as undefined
. This defeats the purpose of using Typescript for type safety.
The reason it happens is that const waldo: Foo
lets the compiler know that waldo
should be of type Foo
.
const waldo = <Foo> {}
is just telling compiler that take a generic object, treat it as Foo
and assign it to waldo
.
Conclusion
Whenever you create an object that should always have the type safety; use const waldo: Foo = {...}
A little homework, do you think the following will provide the type safety or not?
const waldo: Foo = <Foo> {
bar: "Hello",
qux: 7
}
Try it in the Typescript Playground.