February 2019
Beginner
694 pages
18h 4m
English
TypeScript allows us to iterate through the properties of a type and extract the names of its properties through the keyof keyword. keyof will therefore return a string literal made up of property names. Let's explore this concept by starting with an interface, as follows:
interface IPerson {
id: number;
name: string;
surname: string;
}
Here, we have an interface named IPerson that has three properties, named id, name, and surname. If we were to write a function that needs its input limited to the string values "id", "name" and "surname", we could use a string literal as follows:
type PersonPropertyLiteral = "id" | "name" | "surname"; function getKeyOfUsingStringLiteral (ppl : PersonPropertyLiteral, value : IPerson) { console.log(`${ppl} ...Read now
Unlock full access