Похожие чаты

Anyways. If I have discriminated unions in TypeScript, how can I

make them narrow down to a single type using function maps?

Example:

type States = {
name: 'a',
someField: string
} | {
name: 'b',
otherField: boolean
}

const stateChange = (state: States) => {
const stateMap = {
a: () => state.someField,
b: () => state.otherField,
}
return stateMap[state.name]()
}

In the stateMap, TS doesn't know anymore that it was called with stateMap[state.name](). But with if and switch it works. I guess my fancy function maps do not work in this case. Otherwise I have to explicitly give the type for the function, maybe also not so bad.
Anyways, works perfectly with if and that is already great.

3 ответов

5 просмотров

You should be able to cast it more strictly if you find yourself fighting TS inference

Misan- Автор вопроса
Thomas
You should be able to cast it more strictly if you...

Makes sense. I just tried to put unions to a test after reading this article: https://blog.logrocket.com/put-the-typescript-enums-and-booleans-away/

https://www.typescriptlang.org/play?#code/C4TwDgpgBAysCGwIGcoF4oG8CwAoKBUAdvALYQBcUA5PNQDR6FTID25AYgJYQA2AJlWTAATlyIBzPAF8oAHyxNCJclWoAjBkoKtgACwgjufQVHWtWvCPCIy8eAMasiwlgiQBhPTYnQMACmFESlh3FABKdAA+RXxCJxdgN2CAWXgwdFjmZngqQLCqOGDUADIsYjIQ2mooaUi0GKCkADo2Th4BRjjsszymkKKkUvKVKs1a+saw5t0DIw7+LuZpbSgRCGAAVxEiZKQ0sABtfubRgF184Kh4VCIIADdDcIBuO1wgA

Похожие вопросы

Обсуждают сегодня

Есть рассчет для Таллинна? https://x.com/dr_enderlin/status/1784581592003850496
Vladimir Ivanov
23
а зачем этот вопрос для удаления из чата?
Mёdkinson Medvezhkin
63
Добрый день. Хочу сделать отрисовку по команде на панели. Почему-то рисуется только при втором вызове. С чем может быть связано, не подскажете? procedure TForm1.FormDblClick(...
Kirill Filippenok
20
Any dog on Fantom ?
Bitcoin Magic
19
Добрый день Как поставить vscode из флэтпака как дефолтный редактор в filezilla?
Daniel
18
Интересно, а в чём прикол мак оси?
Лисицка
16
main.c #include <fenv.h> #include <stdio.h> int main(void) { constexpr float f = 23.0f; constexpr float g = 33.0f; fesetround(FE_TOWARDZERO); constexpr float...
mito 😼
2
Всем доброго дня! Подскажите может кто использовал связку Pagebuilder + Clientsetting. Сами параметры с типом pagebuilder в модуле Clientsetting работают нормально, можно такж...
Александр Добриков
12
using next image component with s3 image: "url" parameter is valid but upstream response is invalid code: <Image fill src={s...
Fasil
3
Tax his land, Tax his bed, Tax the table At which he's fed. Tax his work, Tax his pay, He works for peanuts Anyway! Tax his cow, Tax his goat, Tax his pants, Tax his coat....
Forge
5
Карта сайта