typescriptintermediate
TypeScript Type System
Utility types, type guards and type inference
7 questions
By EZ4Code Team
1. What does Partial<T> do?
Makes all properties of T optional
Makes all properties of T readonly
Removes some properties of T
Turns T into a union type
Explanation: Partial<T> makes all properties of T optional (adds ?), commonly used to update partial fields of an object.
2. What does Readonly<T> do?
Makes all properties of T readonly
Makes all properties of T optional
Makes T non-instantiable
Freezes the object at runtime
Explanation: Readonly<T> makes all properties readonly (adds readonly), preventing assignment at compile time; runtime immutability requires Object.freeze.
3. Which of the following is a type guard?
function fn(x: string | number) {
if (typeof x === 'string') {
x.toUpperCase()
}
}typeof x === 'string'
x as string
<string>x
x instanceof string
Explanation: typeof is a type guard that narrows x to string within the branch; as is a type assertion without runtime checking.
4. What does Pick<T, K> do?
Picks properties from T whose keys are in K to form a subtype
Removes property K from T
Merges T and K
Converts T to a tuple
Explanation: Pick<T, K extends keyof T> selects properties from T whose keys are in K to construct a new type; Omit is its complement.
5. What is Omit<T, K> equivalent to?
Pick<T, Exclude<keyof T, K>>
Pick<T, K>
Partial<T>
Readonly<T>
Explanation: Omit<T, K> removes properties from T whose keys are in K, equivalent to Pick<T, Exclude<keyof T, K>>.
6. What does the instanceof type guard do?
Narrows to an instance type of a class
Checks primitive types
Asserts a type
Declares a variable
Explanation: instanceof narrows a variable to the instance type of the right-side constructor within a branch, commonly used for class instance checks.
7. What is the difference between unknown and any?
unknown is a safe top type that requires type checking before use; any completely skips checks
They are completely identical
any is safer than unknown
unknown can be used arbitrarily
Explanation: unknown is a type-safe top type that must be narrowed via type guards before use; any abandons type checking and is unsafe.