#An assert-guard to ensure item is in the enum

13 messages · Page 1 of 1 (latest)

winter kraken
#

...

steady groveBOT
#
onkeltem#0

Preview:ts function assertEnumItem<T extends object>( item: unknown | undefined, enumType: T, enumName: string ): asserts item is T | undefined { if (!Object.values(enumType).includes(item as T)) { throw new Error( `Unknown ${enumName} item: "${item}"` ) } ...

winter kraken
#

What I don't understand is why the val is of the undefined type at the end?

#

There are two cases:
1)

declare const val: unknown | undefined
assertEnumItem(val, Foo, 'Foo')

This one results to typeof Foo | undefined
2)

declare const val: Foo | undefined
assertEnumItem(val, Foo, 'Foo')

This one results to just undefined

#

This is odd because the item first function parameter is declared as item: unknown | undefined so how it can be "sensitive" to a specific type?

zenith canyon
#

typeof Foo is not the same as Foo

#

for an enum Foo, Foo is one of its members, while typeof Foo refers to the entire enum object

#

their intersection is never

#

for T being typeof Foo, you want asserts item is T[keyof T] | undefined

#

this is a pretty good example of why typeguards are unsafe lol

#

your logic is right, but the typing you wrote for the logic isn't

winter kraken
#

Oh, you're right! Hahah..

#

Thanks @zenith canyon