简体   繁体   中英

How to narrow down an unknown variable to a general Record type?

What else do I need to put in the if condition so that TS accepts the type of the parameter for the function call? The current condition isn't specific enough and throws the error below.

declare const unknownVar: unknown

declare function foo(record: Record<string | number, unknown>): void

if (unknownVar && typeof unknownVar === 'object')
  foo(unknownVar) // error
Argument of type 'object' is not assignable to parameter of type 'Record<string | number, unknown>'.
  Index signature for type 'string' is missing in type '{}'.

One way that you could accomplish this would be to use type predicates .

declare const unknownVar: unknown

declare function foo(record: Record<string | number, unknown>): void

function isObject(input: unknown): input is Record<string | number, unknown> { 
  return typeof input === 'object'
}

if (isObject(unknownVar))
  foo(unknownVar) // no error!

TS Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM