Typeof Type Operator Flashcards

1
Q

Q: How does TypeScript’s typeof operator differ from JavaScript’s typeof operator?

A

A: JavaScript’s typeof is an expression operator that returns a string describing the runtime type of a value. TypeScript adds a type-level typeof operator that works in type contexts to refer to the type of a variable or property.

// JavaScript typeof (expression context)
console.log(typeof "hello");  // Outputs: "string"

// TypeScript typeof (type context)
let s = "hello";
let n: typeof s;  // n has type 'string'

// More complex example
function createPoint() {
    return { x: 10, y: 20 };
}
type Point = typeof createPoint();  // { x: number, y: number }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Q: How can you use typeof with ReturnType and what are its practical applications?

A

The typeof operator is particularly useful when combined with utility types like ReturnType<T> to get the return type of a function. It helps convert value-level functions to their type representations.</T>

// Function value
function fetchUser() {
    return { 
        id: 1, 
        name: "John",
        age: 30 
    };
}

// Getting return type of the function
type FetchUserReturn = ReturnType<typeof fetchUser>;
// type FetchUserReturn = {
//     id: number;
//     name: string;
//     age: number;
// }

// Usage example
const userInfo: FetchUserReturn = {
    id: 2,
    name: "Jane",
    age: 25
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly