Typescript basics part2
What I learned today
We can also apply some typescript to functions:
Here we are expecting the return value to be a type of number
Interfaces can be used for creating custom objects:
Here we are using 'readonly' option to declare that the 'id' value cannot be changed once it is initalized.
the '?' after 'salary' means that the salary value is completely optional.
We can also use 'type' to create custom primitives. Note that we cannot use interfaces for primitives or unions.
Generics are useful when you want to reuse some components using different types. For example, we can reuse a function using a placeholder to take in a number or string.
Here 'numArray' used the generics to create a new array. But once the array is created, you cannot add string types since it has been initialized with the type num.
And finally, a simple example on how to use this in React. There is an easy way to setup your repo to use typescript by using:
And here, we are setting the types for the props a typical React component would receive:
Comments
Post a Comment