I am making a request as follow:
const listCompartmentsRequest: identity.requests.ListCompartmentsRequest = {
compartmentId: id,
compartmentIdInSubtree: true,
}
But I would like to short that long line identity.requests.ListCompartmentsRequest
.
I'm expecting something like that:
const { ListCompartmentsRequest } = identity.requests
const listCompartmentsRequest: ListCompartmentsRequest = {
compartmentId: id,
compartmentIdInSubtree: true,
}
I tried it, however, I'm getting this error:
ListCompartmentsRequest
refers to a value, but is being used as a type here. Did you meantypeof ListCompartmentsRequest
?"
CodePudding user response:
From the MDN documentation for Destructuring assignment:
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Destructuring only applies to values, not types — TypeScript does not currently offer any equivalent kind of syntax. Instead, you can create a new type alias that represents the nested member of the type that you described. Here's an example:
type Identity = {
Requests: {
ListCompartmentsRequest: {
compartmentId: string;
compartmentIdInSubtree: boolean;
};
};
};
type ListCompartmentsRequest = Identity['Requests']['ListCompartmentsRequest'];
const id = '123';
const listCompartmentsRequest: ListCompartmentsRequest = {
compartmentId: id,
compartmentIdInSubtree: true,
};
And if you are targeting a type within a namespace, then you can use dot notation to access the nested type.