value = true; // OK value = 42; // OK value = "Hello World"; // OK value = []; // OK value = {}; // OK value = Math.random; // OK value = null; // OK value = undefined; // OK value = newTypeError(); // OK value = Symbol("type"); // OK
value = true; // OK value = 42; // OK value = "Hello World"; // OK value = []; // OK value = {}; // OK value = Math.random; // OK value = null; // OK value = undefined; // OK value = newTypeError(); // OK value = Symbol("type"); // OK
对unknow类型的变量赋值都被认为是类型正确的
但是当把unknow类型的值赋给其他类型的变量时,则不会像any一样,不受到任何限制:
1 2 3 4 5 6 7 8 9 10 11
letvalue: unknown;
letvalue1: unknown = value; // OK letvalue2: any = value; // OK
type Result = | { success: true, value: unknown } | { success: false, error: Error };
functiontryDeserializeLocalStorageItem(key: string): Result { const item = localStorage.getItem(key);
if (item === null) { // The item does not exist, thus return an error result return { success: false, error: newError(`Item with key "${key}" does not exist`) }; }
letvalue: unknown;
try { value = JSON.parse(item); } catch (error) { // The item is not valid JSON, thus return an error result return { success: false, error }; }
// Everything's fine, thus return a success result return { success: true, value }; }
函数的调用者需要在使用结果之前对类型进行收窄:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
const result = tryDeserializeLocalStorageItem("dark_mode");
if (result.success) { // We've narrowed the `success` property to `true`, // so we can access the `value` property constdarkModeEnabled: unknown = result.value;
if (typeof darkModeEnabled === "boolean") { // We've narrowed the `unknown` type to `boolean`, // so we can safely use `darkModeEnabled` as a boolean console.log("Dark mode enabled: " + darkModeEnabled); } } else { // We've narrowed the `success` property to `false`, // so we can access the `error` property console.error(result.error); }