How can I use a property of an interface as a type for a variable in typescript ??
Here I want to access the property: string
type and use it as a type for a variable but I cannot access it.
interface foo {
bar?: {
baz: {
property: string;
};
};
}
function f(input: foo['bar']['baz']['property']) {
console.log(input);
}
I was trying to find some optional chaining rule for this, but none of the JavaScript chaining methods worked here.
Error
Property 'baz' does not exist on type '{ baz: { property: string; } ' | undefined
CodePudding user response:
To remove | undefined
part from the foo['bar']
type you can use built-in NonNullable
type, then you can access its properties:
function f(input: NonNullable<foo['bar']>['baz']['property']) {
console.log(input);
}
CodePudding user response:
The problem is that foo['bar']
is optional and therefore it can be either undefined
or an interface containing a baz
property. Typescript will not allow you to access foo['bar']['baz']
as a type if foo['bar']
is allowed to be undefined
.
To work around this issue, you can pull the sub-interface out to its own definition:
interface bar {
baz: {
property: string;
};
}
interface foo {
bar?: bar;
}
function f(input: bar['baz']['property']) {
console.log(input);
}