|
| 1 | +// This "test" is to validate the type inference, i.e. only to compile, but not to run. |
| 2 | + |
| 3 | +import filesize from "../filesize"; |
| 4 | + |
| 5 | +// |
| 6 | +// check functions for compilation time, no need to implement |
| 7 | +// |
| 8 | + |
| 9 | +function shouldBeString(x: string) {} |
| 10 | +function shouldBeNumberUnitPair(x: [number, string]) {} |
| 11 | +function shouldBeNumber(x: number) {} |
| 12 | + |
| 13 | +type FilesizeObject = { |
| 14 | + value: number, |
| 15 | + symbol: string, |
| 16 | + exponent: number, |
| 17 | + unit: string, |
| 18 | +} |
| 19 | +function shouldBeObject(x: FilesizeObject) {} |
| 20 | + |
| 21 | +// |
| 22 | +// single possibility (typical) |
| 23 | +// |
| 24 | + |
| 25 | +// direct call |
| 26 | +shouldBeString(filesize(123)); |
| 27 | +shouldBeString(filesize(123, {})); |
| 28 | +shouldBeString(filesize(123, { output: undefined })); |
| 29 | +shouldBeString(filesize(123, { output: "string" })); |
| 30 | +shouldBeNumberUnitPair(filesize(123, { output: "array" })); |
| 31 | +shouldBeNumber(filesize(123, { output: "exponent" })); |
| 32 | +shouldBeObject(filesize(123, { output: "object" })); |
| 33 | + |
| 34 | +// partial |
| 35 | +shouldBeString(filesize.partial({})(123)) |
| 36 | +shouldBeString(filesize.partial({ output: "string" })(123)) |
| 37 | +shouldBeNumberUnitPair(filesize.partial({ output: "array" })(123)) |
| 38 | +shouldBeNumber(filesize.partial({ output: "exponent" })(123)) |
| 39 | +shouldBeObject(filesize.partial({ output: "object" })(123)) |
| 40 | + |
| 41 | +// |
| 42 | +// mutliple possibilities (tricky) |
| 43 | +// |
| 44 | + |
| 45 | +let opt1!: { output: "string" | "array" }; |
| 46 | +const result1 = filesize(123, opt1); // string | [number, string] |
| 47 | +result1 as string |
| 48 | +result1 as [number, string]; |
| 49 | + |
| 50 | +let opt2!: { output: "exponent" | "object" }; |
| 51 | +const result2 = filesize(123, opt2); // number | { ... } |
| 52 | +result2 as number |
| 53 | +result2 as FilesizeObject |
| 54 | + |
| 55 | +// Note: strictNullChecks needs to be true to correctly handle this scenario. |
| 56 | +// If false, the compiler cannot know the return type may be string. |
| 57 | +let opt3!: { output?: "exponent" }; |
| 58 | +const result3 = filesize(123, opt3); // string | number |
| 59 | +result3 as number |
| 60 | +result3 as string |
0 commit comments