This quiz will test what you have learned about creating types in TypeScript.
1.
We have declared a point variable as follows:
const point ={ x:32, y:77};
Will the following assignments generate any type errors?
point.x=40;
point.y=80;
point.z=10;
2.
We have declared a person variable as an object with firstName and level properties as follows:
let person:{ firstName:string, level:"high"|"Medium"|"low"};
We want to use this type in several places in our codebase. What's the best way to do this?
Continue to use the following as the type annotation:
Copy
{ firstName:string, level:"high"|"Medium"|"low"};
Create the following interface. We can then use Person in type annotations for variables that require this type.
Copy
interfacePerson{
firstName:string;
level:string;
};
3.
We need to create a type to represent information about a person containing their first name, surname, and an optional age. What types could we use to represent this structure?
Copy
typePerson={
firstName:string;
surname:string;
age:number;
}
Copy
interfacePerson{
firstName:string;
surname:string;
age:number;
}
Copy
typePerson={
firstName:string;
surname:string;
age?:number;
}
Copy
interfacePerson{
firstName:string;
surname:string;
age?:number;
}
4.
We need to create a type to represent a numeric level that can hold values between 1 and 5. What type can we use to best represent this?
Copy
typeLevel=number;
Copy
interfaceLevel=1|2|3|4|5;
Copy
typeLevel=1|2|3|4|5;
5.
Will a type error occur on any of the level assignments below:
Copy
enumStatus{
Open,
InProgress,
Complete
}
let level:Status;
level =4;
level ="4";
Yes, both assignments will generate type errors
No, both assignments will not generate any type errors
Only, the second assignment will generate a type error
6.
We have the following type:
Copy
typeProduct={
name:string;
bestBeforeDate:Date;
}
A bestBeforeDate doesn't apply to every product though. So, we want to allow this to be null or a date.
What type best represents this?
Copy
typeProduct={
name:string;
bestBeforeDate:Date|null;
}
Copy
typeProduct={
name:string;
bestBeforeDate?:Date;
}
7.
Are the Dog and Apple types structurally equivalent?