Hello,
Can anyone explain what is happening here ?
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
10 messages · Page 1 of 1 (latest)
Hello,
Can anyone explain what is happening here ?
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
@hearty frigate Here's a shortened URL of your playground link! You can remove the full link from your message.
Preview:```ts
type Languages = 'fr' | 'en'
function test<L extends Languages>() {
const thing = 'fr' satisfies Languages
const thing2 = 'fr' satisfies L
}```
Alright I get it now thx !
Do you know a way to check & narrow the type of L here ?
I Guess I would need a separate function ?
Using .some doesn't trigger a ts error in the if condition, but doesn't narrow the type
Preview:```ts
type Languages = 'fr' | 'en'
function test<L extends Languages>(allowedLanguages: L[]) {
const pickedLanguage = 'fr'
if (!allowedLanguages.includes(pickedLanguage)) {
throw new Error('Nope')
}
if (!allowedLanguages.some((item) => item === pickedLanguage)) {
...```
One simple way is to do:
const language = allowedLanguages.find(language => language === pickedLanguage)
Then check the returned language and use it from then on.
I created a new variable with as L, but using find to narrow to type into a new variable is smarter !
Thanks