The object in Typescript – part 2
We can have a object literal or a class, like the follow examples in this post.
The shape that describe this object is { name: string; age: number }
If we have a class example:
Result:
Nice, now let see what happens when we add extra properties, or leave out required ones:
For example we declared age: number and if we don’t insert that property we will see a TypeScript error:
Other example is when we insert a property that is not type declared, this will cause an error:
let myAge: { age: number }
myAge = {
age: 32,
name: 'Cristina Rojas'
}
Result:
// Object literal may only specify known properties, and ‘name’ does not exist in type ‘ { age: numer; } ‘
By Cristina Rojas.