Notbook of Typescript
Oct-2024
How to define a User type as an example
Syntax: type ObjectName = { propertyKey: type; }
as value of string
, number
, boolean
etc…
How to extend a User type
There’s already User type defined, so extending it simply by using &
Then the Student literally is that type now:
How to alter existing type and create new one
Type properties can be omit, picked and partially (re-)defined.
Pick only needed
So the teachers will only have those properties in their orbject type
Omit unnecessary
Does the same result like Pick way, inverted.
Omitting or Picking and also new props
Extends the User object with some of its original properties, plus, two new
Partial’ization
Extends Student as Graduated students list maybe, but makes isLoggedIn
data optional, means that data will be processed or not.
How to combine objects with other types
Teacher has lectures info, that will be responded as an array of Lecture type, and lecture has department info which refers to a data which is Department type.
Referring to existing types
Prevents typo mistaktes that causes by duplicating definition, or in any case to have it programmable.
Gets the type from Student object and defines it as same type to isRetired
property.
Using enums
Not for definin the employess! but instead the type of the user
That will give two-strict-option-as-string property to the students.
Importing and Exporting types
And in the meanwhile the types.ts
file:
Alternativly importing both types and other things
So if there was getUsers
function in types.ts
file it was imported together with the types from there.
Nested declerations
In this example developer can combine two types by using pointing to the existing types then make a new specific object model type safety definition for multiplle the lectures output of the a student. Watch out the extra []
there which points the the type is an array, multiple lectures will be returned.
Exercism.org Exercises
Challenge: Typescript / Resistor Color Duo
Exercise Playground: My Provided Examples