TypeScript Version: 2.1.4
Code
The following code used to work in TS 2.0
type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
function iExpectDigit(d:Digit)
{ }
for (let k: Digit = 1; k < 10; k++) {
iExpectDigit(k); //Error, because K is number
}
I think the new behaviour is correct.
Since k++
is an operation between a digit and a number, it does make sense that k
becomes a number.
The only work around I've come with is
for (let k: Digit = 1; k < 10; k = <Digit>(k + 1)) {
// k is digit
}
or
// in some module
export let digits: Digit[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (let k of digits)
{
// k is digit
}
The second approach is less expressive, but cleaner.
Question
Is there a better way to iterate over primitive values of a custom type ?
I'm not sure what the use case is, but to simultaneously retain the desired type and maintain correctness, I think the following would be appropriate
type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
function iExpectDigit(d: Digit) { }
function isDigit(n: number): n is Digit {
return n > -1 && n < 10 && n === Math.trunc(n);
}
for (let k = 0; isDigit(k); k++) {
iExpectDigit(k);
}
I say maintain correctness because in order to exit the loop in your example, k
must take the value 10
which is not a Digit
.
Most helpful comment
I'm not sure what the use case is, but to simultaneously retain the desired type and maintain correctness, I think the following would be appropriate
I say maintain correctness because in order to exit the loop in your example,
k
must take the value10
which is not aDigit
.