Reputation: 13
Is it possible to do something like:
type TrueType = true;
const someVar = GetTypeValue<TrueType>(); // This is where the value true is written
Is it possible to write other constant values to constant variables like in C++?
Upvotes: 1
Views: 624
Reputation: 3321
In the typescript world it's better to think of it the other way round if you need to use a constant as a runtime value. Define the constant, (so Javascript has it) then derive the type from it (so Typescript has it).
const GREAT_WORD = 'Discombobulate';
type GreatWord = typeof GREAT_WORD;
const SOUNDS_LIKE = 'Onomatopoeia'
const GOINGS_ON = 'Shenanigans'
const ALL_OVER = 'Ubiquitous'
const LESSER_WORDS = [SOUNDS_LIKE,GOINGS_ON, ALL_OVER];
type LesserWord = typeof LESSER_WORDS[number]
function say(word: GreatWord | LesserWord){
console.log(word)
}
say(GREAT_WORD)
say(SOUNDS_LIKE)
say(GOINGS_ON)
say(ALL_OVER)
say('Discombobulate')
say('Shenanigans')
Upvotes: 1
Reputation: 2289
Typing helps at compile time but not at runtime.
You can use this strategy at compile time to get the value safely:
type TrueType = true;
const myTrue: TrueType = true;
Upvotes: 1