Skip to main content
added 18 characters in body
Source Link

Types don't exist at compiler time so typeof will not work, you need some other type of check to test the type at runtime. Typescript has support for this using a custom type-guards

type odds = 1 | 3 | 5 | 7 | 9; type evens = 2 | 4 | 6 | 8 | 0; function isOdd(v: odds | evens) : v is odds { return v % 2 != 0 } declare let n : odds | evens; withEven(n) // invalid here no check has been performed withOdd(n) // invalid here no check has been performed if (isOdd(n)) { n // is typed as odd withEven(n) // invalid here withOdd(n) // valid here we checked it is odd } else { n // is typed as even withEven(n) // valid here we checked it is not odd  withOdd(n) // invalid here } function withEven(n: evens) { } function withOdd(n: odds) { } 

Types don't exist at compiler time so typeof will not work, you need some other type of check to test the type at runtime. Typescript has support for this using a custom type-guards

type odds = 1 | 3 | 5 | 7 | 9; type evens = 2 | 4 | 6 | 8 | 0; function isOdd(v: odds | evens) : v is odds { return v % 2 != 0 } declare let n : odds | evens; if(isOdd(n)) { n // is odd }else { n // is even } 

Types don't exist at compiler time so typeof will not work, you need some other type of check to test the type at runtime. Typescript has support for this using a custom type-guards

type odds = 1 | 3 | 5 | 7 | 9; type evens = 2 | 4 | 6 | 8 | 0; function isOdd(v: odds | evens) : v is odds { return v % 2 != 0 } declare let n: odds | evens; withEven(n) // invalid here no check has been performed withOdd(n) // invalid here no check has been performed if (isOdd(n)) { n // is typed as odd withEven(n) // invalid here withOdd(n) // valid here we checked it is odd } else { n // is typed as even withEven(n) // valid here we checked it is not odd  withOdd(n) // invalid here } function withEven(n: evens) { } function withOdd(n: odds) { } 
Source Link

Types don't exist at compiler time so typeof will not work, you need some other type of check to test the type at runtime. Typescript has support for this using a custom type-guards

type odds = 1 | 3 | 5 | 7 | 9; type evens = 2 | 4 | 6 | 8 | 0; function isOdd(v: odds | evens) : v is odds { return v % 2 != 0 } declare let n : odds | evens; if(isOdd(n)) { n // is odd }else { n // is even }