Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 如何正确设置以object为参数的构造函数定义_Typescript_Oop_Constructor - Fatal编程技术网

Typescript 如何正确设置以object为参数的构造函数定义

Typescript 如何正确设置以object为参数的构造函数定义,typescript,oop,constructor,Typescript,Oop,Constructor,我正在编写一个请求帮助器,我希望在对象中定义自定义属性,而不是将它们设置为参数 因此,我希望下面的代码能够正常工作 import { IRequest } from './request' export default class Request implements IRequest { constructor({baseUrl: string, timeout: string}: object) {} } 接口: export interface IRequest { new

我正在编写一个请求帮助器,我希望在对象中定义自定义属性,而不是将它们设置为参数

因此,我希望下面的代码能够正常工作

import { IRequest } from './request'

export default class Request implements IRequest {
   constructor({baseUrl: string, timeout: string}: object) {}
}
接口:

export interface IRequest {
   new: ({ baseUrl: string, timeout: number }: object): void
}
如果没有type
object
,我可以看到一个错误,它指示构造函数中的参数应该有一个
typedef
,这是公平的-但是当我分配
:object
(如上)时,我得到:
[tslint]变量名与关键字/type[variable name]
冲突


你能告诉我正确的方法吗?我可能对类型定义做了一些错误的事情。尝试了
{[key:string]:any}
,但也不走运。

如果希望它们传递具有属性
baseUrl
timeout
的对象,则需要先命名它,然后键入它。像这样:

//         name: type
constructor(obj: {baseUrl: string, timeout: string}) {}
简化示例:

class Example {
    constructor(obj: { baseUrl: string, timeout: string }) {
        console.log(obj.baseUrl);
        console.log(obj.timeout);
   }
}

const request = new Example({ baseUrl: 'localhost', timeout: '5s' });