I have a function that uses only pointData
object.
interface AllTheDatas{
id: string
pointData: {
square: string
triangle: string
}
}
I'd like to use only the pointData object, but I don't know how to type it in a function argument:
// do something
buildPointData(AllTheDatas.pointData)
function buildPointData(pointData: ?????){
// do something
return `${AllTheDatas.square}--${AllTheDatas.triangle}
}
I tried to use Partial, Pick<AllTheDatas, 'pointData'> but it doesn't work, returning an error expecting the 2 keys and values inside of pointData object.
I know that I can do something like {x: string, y: string} but since I have a AllTheDatas interface, can't I just try to reuse it?
CodePudding user response:
The easiest way is to just extract the type into a separate interface and give it a proper name:
interface PointData {
square: string;
triangle: string;
}
interface AllTheDatas {
id: string;
pointData: PointData;
}
Then you can just use that named type in your function parameter declaration:
function buildPointData(pointData: PointData) {
… // do something
}
An alternative is to refer to a property of the AllTheDatas
type via an indexed access type expression. You can write
function buildPointData(pointData: AllTheDatas["pointData"]) {
… // do something
}