any, unknown, never and review
Three special types complete the week: any, unknown and never. They are for situations where there is no concrete type, and mixing them up is a classic source of mistakes. In one sentence: any turns the compiler off, unknown forces you to check before using, and never represents something that should never happen. Let us look at each one calmly, because the difference between any and unknown marks the quality of TypeScript code.
any: the dangerous escape hatch
A value of type any accepts every operation: you can call it, index it, add it, ask for properties that do not exist. The compiler says nothing. Worse, any is contagious: whatever comes out of an operation with any is also any, and errors hide in a cascade. It exists for compatibility with old JavaScript and for gradual migrations, but in new code it should be avoided. With strict, TypeScript no longer gives it to you for free on untyped parameters; if you want it, you will have to write it yourself.
unknown: the safe alternative
unknown also accepts any value, but unlike any it does not allow you to do anything with it until you check its type. It is the right type for data whose content you do not know: the result of JSON.parse, what arrives from a form, the error in a catch. To use it, you narrow it with typeof, Array.isArray or instanceof, exactly as in the previous lesson.
function loose(value: any) {
return value.foo.bar(); // no error, may crash at runtime
}
function safe(value: unknown): string {
// return value.toUpperCase(); // error: 'value' is of type 'unknown'
if (typeof value === 'string') {
return value.toUpperCase();
}
if (value instanceof Error) {
return value.message;
}
return 'unsupported';
}
const parsed: unknown = JSON.parse('{"ok": true}');
console.log(safe('abc'), safe(new Error('boom')), safe(parsed));never: the impossible
The never type is that of values that never exist. A function that always throws an exception returns never. And above all it appears in narrowing: when you rule out every option of a union, what remains is never. This is used to guarantee exhaustiveness: you assign the leftover value to a never variable, and if one day you add a new case to the union and forget to handle it, the assignment fails at compile time and the error points to the exact place.
type Shape = 'circle' | 'square';
function assertNever(value: never): never {
throw new Error('Unexpected value: ' + String(value));
}
function sides(shape: Shape): number {
switch (shape) {
case 'circle':
return 0;
case 'square':
return 4;
default:
return assertNever(shape); // error if a new Shape is not handled
}
}
console.log(sides('square'));To close the week, remember a practical summary. First, let TypeScript infer whenever it can and annotate the boundaries. Second, describe closed sets of options with unions of literals. Third, narrow before using a value that can have several types. Fourth, prefer unknown over any for unknown data. Fifth, use never so the compiler warns you when you forget a case. If you master these five ideas, you are already writing real TypeScript, and the rest of the course only adds more tools on the same foundation.
理解度チェック
問題 1 / 6What is the main difference between any and unknown?
✎ マイノート
このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字