By @akash_dathan
Type Declaration vs Type Assertions
Simple answer, you should prefer Type Declaration
to Type Assertion
, why? read along…
There are two ways of providing type to a variable in typescript
Let’s see what is the difference between these two methods and when to use which method.
In the below code we are defining an interface called Hero
which will be used
to provide type to the following variables. We are using Type Declaration
to assign
a type to the variable drow
and Type Assertion
to assign a type to the variable centaur
.
interface Hero {
name: string,
type: string
};
// Type Declaration
const drow: Hero = {
name: 'Drow Ranger',
type: 'agility'
};
// Type Assertion
const centaur = {
name: 'centaur warrunner',
type: 'strength'
} as Hero;
In a perfect world, like in the example above, both the objects have the expected fields and there is no difference between both types of type assignment. Let’s see how these works in the following scenarios.
Type Declaration
Type Declaration
verifies that the value conforms to the interface.
Since the following examples do not abide by it, Typescript throws an error.
// Error: Properties missing in the type
const drow: Hero = {};
// Error: 'isAvailable' does not exist on type Hero
const drow: Hero = {
name: 'centaur warrunner',
type: 'strength',
isAvailable: true,
};
Type Assertion
Type Assertion
tells the type checker that you understand the types better than it and to not throw an error.
// No Error
const drow = {} as Hero;
// No Error
const drow = {
name: 'centaur warrunner',
type: 'strength',
isAvailable: true,
} as Hero;
So, in conclusion, you should use Type Declaration
over Type Assertion
because they provide
additional safety checks. Unless you have a specific use case to use Type Assertion
Thats all folks, happy hacking 🙌