- We have an interface that represents a course result as follows:
interface ICourseMark {
courseName: string;
grade: string;
}
We can use this interface as follows:
const geography: ICourseMark = {
courseName: "Geography",
grade: "B"
}
The grades can only be A, B, C, or D. How can we create a stronger typed version of the grade property in this interface?
We can use a union type:
interface ICourseMark {
courseName: string;
grade: "A" | "B" | "C" | "D";
}
- We have the following functions, which validate that numbers and strings are populated with a value:
function isNumberPopulated(field: number): boolean {
return field !== null && field !== undefined;
}
function isStringPopulated(field: string): boolean {
return field !== null && field !== undefined && field !== "";
}
How can we combine these into a single function called isPopulated with signature overloads?
We can use overload signatures and then a union type for field in the main function. We can then use the typeof type guard in the function to deal with the different branches of logic:
function isPopulated(field: number): boolean
function isPopulated(field: string): boolean
function isPopulated(field: number | string): boolean {
if (typeof field === "number") {
return field !== null && field !== undefined;
} else {
return field !== null && field !== undefined && field !== "";
}
}
- How can we implement a more flexible version of the isPopulated function with generics?
We can use a generic function with a typeof type guard for the special branch of code for strings:
function isPopulated<T>(field: T): boolean {
if (typeof field === "string") {
return field !== null && field !== undefined && field !== "";
} else {
return field !== null && field !== undefined;
}
}
- We have the follow type alias of stages:
type Stages = {
pending: 'Pending',
started: 'Started',
completed: 'Completed',
};
How can we programmatically turn this into the union type 'Pending' | 'Started' | 'Completed'?
We can use the keyof keyword:
type StageUnion = keyof Stages
- We have the following union type:
type Grade = 'gold' | 'silver' | 'bronze';
How can we programmatically create the following type?
type GradeMap = {
gold: string;
silver: string;
bronze: string
};
We can map the type as follows:
type GradeMap = { [P in Grade]: string }