简体   繁体   English

当我有一个嵌套接口并且我只想获取 object 时,如何在 function 的参数中定义?

[英]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.

相关问题 我是否必须使用接口来使用typescript定义对象的元素? - Do I have to use an interface to define the elements of an object with typescript? 如何在 function 中使用 generics 获得嵌套接口值? - how do I get nested interface value with generics inside a function? 为函数定义接口,我无权访问声明 - Define Interface for function, for which I do not have access to the declaration 如何为也是对象的构造函数定义打字稿接口? - How do I define an typescript interface for a constructor that also is an object? 如何为包含键/值对以及嵌套对象的对象/数组定义接口? - How can I define an interface for a object/array containing key/value pairs as well as nested objects? 如何推断嵌套参数类型? - How do I infer nested argument type? 打字稿:如何为对象类型的键值对定义接口 - Typescript: How do I define an interface for an object type's key value pair 当我想使用文件缓冲区调用函数时,我必须使用哪种打字稿类型? - Which typescript type do I have to use when I want to call a function with file buffer? 打字稿:如何为嵌套(嵌套)对象定义接口? - Typescript: How do I define interfaces for nested (nested) objects? 如何为空数组定义TypeScript接口? - How do I define a TypeScript interface for an empty array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM