Home > database >  How to fix this typescript reference error
How to fix this typescript reference error

Time:02-19

I am seeing typescript error with following code even though i mentioned as Record<"abc", string> ?

interface IFoo {
  key ?:
    | string
    | Record<"abc", string>
    | boolean
    | string[]
}
const test: IFoo = {key: {abc: "Hi"}}
console.log(test?.key?.abc);

Property 'abc' does not exist on type 'string | Record<"abc", string>'.
  Property 'abc' does not exist on type 'string'.

https://www.typescriptlang.org/play?ssl=8&ssc=1&pln=1&pc=1#code/JYOwLgpgTgZghgYwgAgJIDED2nkG8CwAUMsgNYQCeyA-AFxEkkA yAzmFKAOYOMsBKEBJigATADwAiOACMEkgDRsO3AHxEAvkWEh2ySO1posOALx5yFI7lkIjkgBLBJGrYR2tMAGwgA6L5hcABQGYNS luG2AJQA3ERAA

CodePudding user response:

Since test?.key can be something else other than Record<"abc", string>, you can't access the property abc.

You could use a type coercion or type guards instead:

const key = test?.key;

if (isAbcRecord(key)) console.log(key.abc);

function isAbcRecord(v: unknown): v is Record<"abc", string> {
    return v && typeof v === "object" && !Array.isArray(v); // should suffice
}

CodePudding user response:

I would go for restricted generics:

interface IFoo <T extends  string
    | Record<"abc", string>
    | boolean
    | string[]>{
  key ?:T
}
const test: IFoo<Record<"abc",string>> = {key: {abc: "Hi"}}
console.log(test?.key?.abc);
  • Related