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'.
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);