Middle
How to determine if a value of type unknown is a specific named type? How to make TypeScript understand that the check has been performed (type guard)?
sobes.tech AI
Answer from AI
To determine that a value of type unknown matches a specific named type in TypeScript, you need to write a type guard function. Such a function checks the structure or properties of an object and informs the compiler that after the check, the value has the desired type.
Example: suppose there is an interface
interface User {
name: string;
age: number;
}
And there is a value value: unknown. To check that value is a User, we write a function:
type User = { name: string; age: number };
function isUser(value: unknown): value is User {
return typeof value === 'object' && value !== null &&
'name' in value && typeof (value as any).name === 'string' &&
'age' in value && typeof (value as any).age === 'number';
}
Here, value is User is a special syntax that tells TypeScript that if the function returns true, then value can be considered of type User.
Usage:
const data: unknown = getData();
if (isUser(data)) {
// Here, TypeScript knows that data is a User
console.log(data.name);
} else {
// data is not a User
}
Thus, a type guard allows safe working with the unknown type by refining it to a specific named type.