Skip to content

Instantly share code, notes, and snippets.

@okumurakengo
Created December 18, 2019 04:58
Show Gist options
  • Save okumurakengo/95f9969d8355cf30bd343354102e0eef to your computer and use it in GitHub Desktop.
Save okumurakengo/95f9969d8355cf30bd343354102e0eef to your computer and use it in GitHub Desktop.
ts unknown test
let value1: any;
value1 = true; // OK
value1 = 42; // OK
value1 = "Hello World"; // OK
value1 = []; // OK
value1 = {}; // OK
value1 = Math.random; // OK
value1 = null; // OK
value1 = undefined; // OK
value1 = new TypeError(); // OK
// Math.max(...value1); // コンパイルOK、実行時にnumberの配列でないとエラーになる
let value2: unknown;
value2 = true; // OK
value2 = 42; // OK
value2 = "Hello World"; // OK
value2 = []; // OK
value2 = {}; // OK
value2 = Math.random; // OK
value2 = null; // OK
value2 = undefined; // OK
value2 = new TypeError(); // OK
value2 = [1, 2, 3];
Math.max(...value2); // Type 'unknown' is not an array type. ←unknownだとエラーになってくれるので型安全!
if (isNumberArray(value2)) {
console.log(Math.max(...value2)); // numberの配列のチェック後などに実行可能!
}
function isNumberArray(value: unknown): value is number[] {
return (
Array.isArray(value) &&
value.every(element => typeof element === "number")
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment