Typeof
An operator that converts data to a type as shown below
Generic data → Convert to a generic type
Object data → Convert to an object's type to the type of the object
Method → Converts to the type of the method
Class → Converts to the type of the class
Converts general data to a general type
Used as a type guard
const name = 'kim'
// typeof name returns a string
if (typeof name === 'string') {
console.log('This is of type string');
}
Example of converting an object to a type
For example, convert 1 below to 2 (you can see it at once by looking at 2)
// 1
const obj = {
red: 'apple',
yellow: 'banana',
};
type Fruit = typeof obj;
// 2
/* /*
type Fruit = {
red: string;
yellow: string;
}
*/
let obj2: Fruit = {
red: 'pepper',
yellow: 'orange',
};
Example of converting a method to a type
// 1
function fn(num: number, str: string): string {
return num.toString();
}
} type Fn_Type = typeof fn;
// 2
/* type Fn_Type = (num: number, str: string) => string */
const ff: Fn_Type = (num: number, str: string): string => {
return str;
};
Example of converting a class to a type
// 1
class Classes {
constructor(public name: string, public age: number) {}
}
// 2
type Class_Type = Classes;
/* type Class_Type = { name: string, age, number } */
const cc: Class_Type = {
name: 'Name',
age: 20,
};
Keyof
An operator that converts to a type as shown below
Object type → Object key value to Union type
Example of changing the type of an object to a Union of key values
type Type = {
name: string;
age: number;
}
} type Union = keyof Type;
// type Union = name | age
Example of keyof and typeof being used together
Example of changing an object's data → object's type → object's key value to a Union type
const obj = { red: 'apple', yellow: 'banana' } as const; // To construct a constant type, we make a type assertion.
// typeof is applied first to get { red: string, yellow: string }
// then keyof is applied, resulting in red | yellow
// So the type Color is red | yellow
type Color = keyof typeof obj;
Example of how keyof is used in Generic
For example, here's a situation where the first argument is an object and the second argument is a key value of the first argument's object.language="text" class="toastui-editor-ww-code-block">
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
let x = { a: 1, b: 2, c: 3, d: 4 };
getProperty(x, "a"); // success
getProperty(x, "m"); // Error: Argument type 'm' does not correspond to 'a' | 'b' | 'c' | 'd'
Summary
typeof data → type (data to type)
keyof object type → key value extraction and change to union type (object type's key value to union type)
Reference