Borislav Hadzhiev
Wed Feb 16 2022·2 min read
Photo by Doug Robichaud
Use type assertions to initialize a typed variable to an empty object, e.g.
const a1 = {} as Animal;
. You can then set the properties on the object using
dot or bracket notation. All of the properties you set on the object need to
conform to the type.
type Animal = { name: string; age: number; }; const a1 = {} as Animal; a1.name = 'Tom'; a1.age = 3;
We used a type assertion to declare an empty object for a typed variable.
This is often the case when fetching data from a remote source like a database. In this situation, you can use a type assertion to cast the variable to a specific type.
If you try to add a property to the object that doesn't conform to the type, you'd get an error.
type Animal = { name: string; age: number; }; const a1 = {} as Animal; a1.name = 'Tom'; a1.age = 3; // ⛔️ Error: Property 'test' does not exist on type Animal a1.test = 'hello';
We've set the a1
variable to be of type Animal
, so trying to set a test
property on the object gets us an error.
However, one thing to be aware of is - you're not required to set all of the required properties of the specific type once you've used a type assertion.
type Animal = { name: string; age: number; }; const a1 = {} as Animal; a1.name = 'Tom'; // ✅ No error, all good
We've only set the name
property on the empty object, but the Animal
type
requires us to set an age
property that is a number
.
In this scenario, TypeScript doesn't warn us, because we've already told it that
we have more information about the type of the value and it is in fact of type
Animal
.
An alternative approach is to use the Partial
utility type to set all of the
properties of the specific type to optional.
type Animal = { name: string; age: number; }; // 👇️ a1: {name?: string; age?: number} const a1: Partial<Animal> = {}; a1.name = 'Tom'; // ✅ No error, all good
The Partial utility type enables us to set all of the properties of the type to optional.
This way we can declare the typed variable to an empty object without getting an error.
Animal
type are optional.If you try to set a property on the object that doesn't conform to the type, you'd still get an error.
type Animal = { name: string; age: number; }; const a1: Partial<Animal> = {}; a1.name = 'Tom'; // ✅ No error, all good // ⛔️ Error: "300" is not assignable to type "number" | "undefined" a1.age = '300'; // ⛔️ Error: Property 'test' does not exist on type Animal a1.test = 'hello';