DEV Community

Discussion on: Type | Treat 2021 - Day 1

Collapse
 
jaycruz profile image
JayCruz

I figured out the beginner Day 1 Solution but don't fully understand how the typeof trick on the song param works.

Collapse
 
tusharar091 profile image
tusharar091

Basically if you don't assert array 'as const' , typescript will infer it as a string array meaning any string whether it is a song from the playlist or not will be perfectly valid. When you use "type of playlist[number]" to define the type of the song param, that means you have a created your own type which will only limit the values to the "songs which are part of your playlist array", so if you pass any other string or make a typo , compiler will through you an error.

e.g :-
const keywords=['var','let','const'] as const;

function getKeyword(keyword:string){
return keywords.find(a=>a===keyword);
}
getKeyword('var') //Valid
getKeyword('let') //Valid
getKeyword('cout') //Returns undefined.

To limit keyword:string parameter to include only 'var|let|const' as values you can use typeof keywords[number] and modify your code like this.

function getKeyword(keyword:typeof keywords[number]){
return keywords.find(a=>a===keyword);
}
getKeyword('var') //Valid
getKeyword('let') //Valid
getKeyword('cout') //TS throws compilation error.

Collapse
 
jaycruz profile image
JayCruz

Thanks! It sounds like by saying typeof keywords[number] your saying, get the values from the indexes of that const.