Typescript: Question/Idea : Iterate over primitive values of a custom type

Created on 11 Dec 2016  ·  1Comment  ·  Source: microsoft/TypeScript

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 kbecomes 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 ?

Question

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

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.

>All comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jbondc picture jbondc  ·  3Comments

siddjain picture siddjain  ·  3Comments

dlaberge picture dlaberge  ·  3Comments

uber5001 picture uber5001  ·  3Comments

remojansen picture remojansen  ·  3Comments