[英]How do I define in a argument of a function when I have a nested interface and I want to get only the object?
I have a function that uses only pointData
object.我有一个 function,它只使用
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:我只想使用 pointData object,但我不知道如何在 function 参数中输入它:
// 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.我尝试使用 Partial, Pick<AllTheDatas, 'pointData'> 但它不起作用,返回一个错误,期望 pointData object 中的 2 个键和值。
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?我知道我可以做类似 {x: string, y: string} 的事情,但是因为我有一个 AllTheDatas 接口,我不能尝试重用它吗?
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 参数声明中使用该命名类型:
function buildPointData(pointData: PointData) {
… // do something
}
An alternative is to refer to a property of the AllTheDatas
type via an indexed access type expression .另一种方法是通过索引访问类型表达式引用
AllTheDatas
类型的属性。 You can write你可以写
function buildPointData(pointData: AllTheDatas["pointData"]) {
… // do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.