Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.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
将api服务更新为typescript-TS2339:Property';实例';不存在于类型';Http';_Typescript_Vue.js_Vuejs3 - Fatal编程技术网

将api服务更新为typescript-TS2339:Property';实例';不存在于类型';Http';

将api服务更新为typescript-TS2339:Property';实例';不存在于类型';Http';,typescript,vue.js,vuejs3,Typescript,Vue.js,Vuejs3,为什么我的实例说它在Http上不存在 我使用我的实例返回我要进行的axios调用的类型-get/post等等 constructor(baseURL: string, headers = {}, config = {}, interceptors = null, timeout = 8000) { this.instance = axios.create({ headers, timeout, baseURL, ..

为什么我的实例说它在Http上不存在

我使用我的实例返回我要进行的axios调用的类型-get/post等等

    constructor(baseURL: string, headers = {}, config = {}, interceptors = null, timeout = 8000) {
    this.instance = axios.create({
        headers,
        timeout,
        baseURL,
        ...config,
    });

    if (interceptors) {
        interceptors.hook(this.instance);
    }
}
类型“Http”上不存在属性“instance” 在typescript中创建类时,需要声明所有类属性及其类型

import axios, {AxiosInstance, AxiosRequestConfig} from "axios";

class Http {
    public instance: AxiosInstance;

    /* ...  */
}
当使用无主体构造函数将构造函数参数设置为实例变量时,可以绕过此要求。但是在本例中,您正在构造函数中创建一个属性,因此需要在类的顶层声明它

对象可能为“null” 此外,您需要为某些构造函数参数声明类型,因为它们无法正确推断。基本上,typescript采用默认值的类型,并假定默认值的类型是参数的类型。因此
timeout=8000
是可以的,因为
timeout
被假定为
number
(尽管我个人为了一致性还是添加了类型)

但是
interceptors=null
会引起问题,因为typescript不知道
interceptors
的类型应该是什么,而它不是
null
。实际上,它将
拦截器的类型指定为
null
,因此即使在检查它是否存在后,您仍然会得到一个错误
对象可能为“null”

您可能已经在代码库中的某个位置有了此对象的类型,但仅基于此代码段,它就必须有一个属性
hook
,该属性可以引用您的实例:

interface Interceptors {
    hook( instance: AxiosInstance ): void;
}
为了使用
null
作为默认值,我们必须说这个变量可以是,aka
拦截器| null

对于头文件和配置文件,需要输入axios可以接受的内容
AxiosRequestConfig
实际上说头可以是
any
,但让我们将其限制为字符串键控对象。对于配置,我们将只使用从axios导入的
AxiosRequestConfig
类型。我们可以得到我们要覆盖的花式和属性,但这是不必要的,因为它们已经是可选的了

正确类型的构造函数可能类似于

    constructor(
        baseURL: string,
        headers: Record<string, any> = {},
        config: AxiosRequestConfig = {},
        interceptors: Interceptors | null = null,
        timeout: number = 8000
    ) {
构造函数(
baseURL:string,
标题:记录={},
config:AxiosRequestConfig={},
拦截器:拦截器| null=null,
超时:数字=8000
) {

非常感谢您的深入解释。我正在慢慢地尝试弄清楚TS…解释得非常好。我的拦截器有您所说的属性挂钩,但我有点困惑您是如何反转它的。您能解释一下您是如何处理这个问题的吗?@EliasMarcoLip如果您想弄清楚变量需要是什么,请看看您是如何使用的假设axios中的拦截器对象有很多方法,但我们在这里需要的唯一功能是执行这一行:
interceptors.hook(this.instance)
我们知道我们给它的参数类型,我们知道我们不需要任何返回值。如果您将参数定义为所需的最小接口,它会使您的代码更加灵活,因为您可以使用
hook
方法作为拦截器传入任何对象。这只是一个一般的OOP原则/想法。