You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
interfaceMessage{text: string;}functionisMessage(value: unknown): value is Message{returnvalue!==null&&typeofvalue==='object'&&typeofvalue.type==='string';}
On the surface this is pretty straightforward and how you'd normally do type guards in any language, but:
Moving the null check after the 'object' type check, fixes the first error, even if that shouldn't change anything.
If you use an intermediary Record<string, unknown> type, you can access that type without errors
interfaceMessage{text: string;}functionisObject(value: unknown): value is Record<string,unknown>{returntypeofvalue==='object'&&value!==null;}functionisMessage(value: unknown): value is Message{returnisObject(value)&&typeofvalue["type"]==='string';}
I think this isObject type guard is necessary in every type guard until TypeScript decides that object is actually Record<string, unknown> | null like one would expect.
Type guards are hard:
On the surface this is pretty straightforward and how you'd normally do type guards in any language, but:
Fun facts:
null
check after the'object'
type check, fixes the first error, even if that shouldn't change anything.Record<string, unknown>
type, you can access thattype
without errorsI think this
isObject
type guard is necessary in every type guard until TypeScript decides thatobject
is actuallyRecord<string, unknown> | null
like one would expect.Related:
PlainObject
#107The text was updated successfully, but these errors were encountered: