Issue
I'm new to TS and I would like to create a custom type
I want to have a custom type (Numbers_2) that accepts some numbers plus the value stored in some variable (n1) and have it work the same way Numbers_1 would
let n1 = 40;
type Numbers_1 = 10 | 20 | 30 | 40;
type Numbers_2 = 10 | 20 | 30 | n1; // 'n1' refers to a value, but is being used as a type here. Did you mean 'typeof n1'?
let n2: Numbers_2 = 1230; // This line should signal a problem
Help much appreciated!
Solution
You can, by using TypeScript's typeof
type-operator (which is not the same thing as JavaScript's typeof
operator), but you then also need to change let n1
to const n1
because when n1
is mutable the typeof n1
is number
instead of the literal value.
const n1 = 40;
type Numbers_1 = 10 | 20 | 30 | 40;
type Numbers_2 = 10 | 20 | 30 | typeof n1;
let n2: Numbers_2 = 1230;
...which results in an error on line 4, which is what your post expects:
Type '1230' is not assignable to type '
Numbers_2
'.
If you want or need n1
to be mutable, then what you're asking is impossible, by way of demonstration:
let n1 = parseInt( prompt( "What is the answer to the Ultimate Question of Life, The Universe, and Everything?" ), 10 );
type Numbers_1 = 10 | 20 | 30 | 40;
type Numbers_2 = 10 | 20 | 30 | typeof n1; // `n1: number`
let n2: Numbers_2 = 1230; // OK
typeof n1
has to be number
because parseInt
returns number
- which in-turn means that type Numbers_2
is 10 | 20 | 30 | number
which means that let n2: Numbers_2 = 1230;
is valid and okay.
If you need a number
-typed "input" variable but still want Numbers_2
to be constrained to a small set of known, possible values then you'll need to explicitly narrow it, like so:
type TheAnswer = 42;
type Numbers_2 = 10 | 20 | 30 | TheAnswer;
function isNumbers2( x: number ): x is Numbers_2 {
switch( number ) {
case 10:
case 20:
case 30:
case 42:
return true;
default:
return false;
}
}
//
// `n1` has type `number`
let n1 = parseInt( prompt( "What is the answer to the Ultimate Question of Life, The Universe, and Everything?" ), 10 );
if( isNumbers2( n1 ) ) {
// Only within the scope of this `if` statement, `n1` has type `Numbers_2`
}
Answered By - Dai
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.