- This is the Typescript playground of useful examples that can save you a lot of time and help you master Typescript with effective type safety implementation covering the cases that usually bother you when you encounter them.
- These cases can significantly improve your knowledge of Typescript and help you excel at it.
- Many of these cases are usually asked during the interview
1. Let’s discuss a case where you have a variable which accepts an array and this array will always have the first element as a string and the rest of the elements will be an object containing the id and name.
Let’s understand it with an example
The IData interface can be used to define the dataArray whose first element will always be a string and all other elements from index 1 and so on will be an object with an id and name as keys.
interface IData = [string, …{id:number,name:string}[]]let dataArray: IData = [‘hello string’,{id:1,name:’david’},{id:2,name:’sevin’},{id:3,name:’viton’}]
|
|
interface Data = [string, ...{id:number,name:string}[]] to leave data table:Data = [‘hello string’,{id:1,name:’david’},{id:2,name:’sevin’},{id:3,name:’viton’}] |
2. Suppose we have a function that accepts a parameter that can have objects with different keys so we can write a generic definition for the function
We create a function to validate whether the object has null values or not. There are two objects with their types defined below.
The two objects have different keys but they use a single generic function to validate whether a key in the object has a null value.
obj1 has a null value for company so the isvalid() function will return false and obj2 does not have a null value so the function will return true.
As you can see the isvalid arg function parameter has a generic type like objType which can accept any object with any key.
Check the example below
type objtype1={company:string | null; PIN code: number; } type objtype2 ={employeeCount:number; isHiring:boolean; department: null | chain; } const obj1:objtype1 ={ company:null, pincode:23 } const obj2:objtype2={employeeCount:1000, isHiring:false, department:’IT’ } function isvalid
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
type object type1={ business:chain | null; PIN code:number; } type objecttype2 ={ Number of employees:number; Hiring :boolean; department:null | chain; } const obj1:object type1 ={ business:null, PIN code:23 } const obj2:objecttype2={ Number of employees:1000, Hiring:FAKE, department:‘HE’ } function I love you<Type>(argument:Type):boolean{ For(const key In argument){ if(argument[key]===null){ back FAKE; } } back TRUE; } console.save(I love you<object type1>(obj1)); console.save(I love you<objecttype2>(obj2)); |
3. If you want to create a new type by extracting keys from another interface but you don’t need to extract all keys, we can use Exclude type of utility to remove unwanted keys as shown below.
We need to create a new type that only has ‘id’, ‘name’, ‘canWork’ as accepted string values and excludes ‘comment’.
So using key of we extracted the keys from the data object then using Exclude we excluded the key comment and created a new type called newData which will have the following structure
type newData = { ‘id’, “name”, “canWork” }
type data = { id:number; name:string; canWork:boolean; comment :string; } type newData = Exclude
|
|
type data = { identifier:number; name:chain; can work:boolean; comment :chain; } type newData = Exclude<key of data,‘comment‘> |
Javascript object keys are always constrained to a string, so the object[0] is always the same as the object[“0”].
4. What is the difference between Exclude and Omit utility types.
In the example above from the 3rd point, we saw that Exclude requires two parameters. The 1st parameter accepts the string union and the second parameter includes the string union which must be removed from the first parameter to create a new type.
Omit does the same thing but it requires the first parameter as an object as a key-value pair and the second parameter is the union of keys which we need to remove from the first parameter’s object.
In the same way Take And Extract Utility types work.
Let’s understand Omit with example
In the example below, there is All interface with four properties. Now we need to create a new type called TodoOverview of the Todo interface but it only needs two Todo properties. So we used Omit to remove “note” and “done”.
Now TodoPreview will be { title: string; createdTo: number; }
interface Todo { title: string; note: string; completed: boolean; createdTo: number; } type TodoPreview = Omit
|
|
interface All { title: chain; note: chain; completed: boolean; created at: number; } type TodoOverview = Omit<All, “note” | “completed”>; const all: TodoOverview = { title: “Hotel”, created at: 162554425273, } |
5. How to create type as conditional types in Typescript
Here we will define three types EmployeeProps, teamLeadProps and dataProps.
dataProps has the name property as mandatory with either employeeProps Or teamLeadProps will be needed to make typescript happy if you assign the dataProps type to any variable.
Suppose we have a function printData() which accepts the type parameter dataProps.
We can now call this function in two ways.
First case – We need to pass three properties in the parameters. ‘name’ is mandatory. If we pass the designation as ‘partner‘ then we need to pass the mandatory key as nameOfLead.
Second case – In this case too ‘name’ is mandatory and if we pass the designation as ‘team leader’ then it will be obligatory to pass the ‘manager name’ Also.
You can see the example below where we have passed the third parameter conditionally based on the designation.
This is a very useful use case in many scenarios. In many cases of typescript react, this conditional typing is required when the parent component needs to pass the props conditionally to its child component.
type EmployeeProps = { designation: ‘associate’; nameOfLead:string; } type teamLeadProps = { designation: ‘teamLead’; ManagerName: string; } type dataProps = { name:string; } & (employeeProps | teamLeadProps ) function printData(params:dataProps){ if(params.designation === ‘teamLead’){ console.log(params.nameOfManager) }else{ console.log(params.nameOfLead) } } printData ({name: ‘kai’, designation: ‘teamLead’, nameOfManager: ‘linda’}) printData({name: ‘Bin’, designation: ‘associate’, nameOfLead: ‘jess’})
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
type employeeProps = { designation: ‘partner’; NameOfLead:chain; } type teamLeadProps = { designation: ‘team leader’; managername:chain; } type dataProps = { name:chain; } & (employeeProps | teamLeadProps ) function printData(settings:dataProps){ if(settings.designation === ‘team leader’){ console.save(settings.managername) }other{ console.save(settings.NameOfLead) } } printData({name:‘Kai’,designation:‘team leader’,managername:‘linda’}) printData({name:‘garbage can’,designation:‘partner’,NameOfLead:‘Jess’}) |