简体   繁体   English

如何在参数中定义 object 数据类型?

[英]How do I define object data type in parameter?

My code like this:我的代码是这样的:

public async index(params: any) {
    return params
}

return params like this:像这样返回参数:

{
    "data": {
        "params": {
            "task_id": 101
        }
    }
}

I want to define object data type in parameter.我想在参数中定义 object 数据类型。 So it does not use any所以它不使用any

I try like this:我尝试这样:

public async index(params: object) {
    return params
}

But there exist message: Property 'params' does not exist on type 'object'但存在消息: Property 'params' does not exist on type 'object'

How can I solve this problem?我怎么解决这个问题?

You can solve this problem by defining an own type that fits your object.您可以通过定义适合您的 object 的自己的类型来解决此问题。 In your example, this would be:在您的示例中,这将是:

type paramsType = {
   data: {
      params: {
         task_id: number
      }
   }
}

Then you can write (params: paramsType).然后你可以写(参数:paramsType)。 Let me know if this works.让我知道这个是否奏效。 :) :)

Try like this:试试这样:

type myParamsType = {
   data: {
      params: {
         task_id: number
      }
   }
}

public async index(params: myParamsType) {
    return params;
}

// Use like this.

myParams: myParamsType = {
    "data": {
        "params": {
            "task_id": 101
        }
    }
};

index(myParams);

You can also define a class instead of a type.您还可以定义 class 而不是类型。 Depedns of what you have to do with datas.取决于您对数据的处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何定义唯一的按钮类型? - How do I define a unique button type? 如何使用参数在对象上定义函数? - How do I define a function on an object with parameters? 打字稿:如何为对象类型的键值对定义接口 - Typescript: How do I define an interface for an object type's key value pair 如何解决 typescript 错误在“对象”类型上找不到带有“字符串”类型参数的索引签名 - How do i solve typescript error No index signature with a parameter of type 'string' was found on type 'Object' 在JS中,如何使用字符串定义JS对象参数? - In JS, how can I use a string to define a JS object parameter? 如何使用 Axios 定义是否需要参数? - How do I define whether a parameter is required or not using Axios? 如何在Graphql中返回JSON对象并定义JSON类型 - How can I return a JSON object in Graphql and define JSON type 如何在返回的 pipe(map(...)) 语句中定义 object 类型? - How can I define the object type in a returned pipe(map(...)) statement? 如何定义具有重复结构的 typescript 类型? - How do I define a typescript type with a repeating structure? 为 function 参数定义 object 类型/在 VS 代码中自动完成 - Define object type for function parameter / get auto completion in VS Code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM