为什么变量类型变为任何类型?

问题描述

更新1:

mxGraph.d.ts完整代码:

declare module 'mxgraph' {

  class mxGraph {

    constructor(container: HTMLElement);
  
  }
}

index.d.ts的完整代码:

declare module 'mxgraph' {
  export interface mxGraphExportObject {
    mxGraph: typeof mxGraph;
  }

  export type mxGraphOptions = {
    mxBasePath?: string;
  };

  export default function (options?: mxGraphOptions): mxGraphExportObject;
}

我正在为mxgraph包创建类型声明库,主要代码是:

declare module 'mxgraph' {
  export interface mxGraphExportObject {
    mxGraph: typeof mxGraph;
    // ...
  }

  export type mxGraphOptions = {
    mxBasePath?: string;
    // ...
  };

  export default function (options?: mxGraphOptions): mxGraphExportObject;
}

在我的项目中使用时,所有属性类型均为any命名空间下的mx

import mxgraphFactory from 'mxgraph';

const mx = mxgraphFactory({
  mxBasePath: 'assets',});

mx.mxGraph;

enter image description here


mx的类型有效。

enter image description here


解决方法

为什么变量类型变为任意类型?

您不应该使用typeof运算符。 typeof返回值的类型,因此可以是任何值。

考虑以下示例:

const foo: any = "bar";

type Foo = {
    bar: string;
}

type FooBar = {
    foo: typeof foo; // should not use typeof here
}

const foobar:FooBar = {
    foo: "abc"
};

foobar.foo

此处foobar.foo是any类型,在typescript中仍然有效。尽管typeof并不是那样使用的。

enter image description here

解决方案:

首先定义MxGraph类型,然后

export interface mxGraphExportObject {
    mxGraph: MxGraph;
    // ...
  }
,

尝试之后,我发现了原因,index.d.ts应该使用/// <reference path="..." />来引用其他声明文件。此提交可解决问题https://github.com/typed-mxgraph/typed-mxgraph/commit/244b0124ae46d09793f4cb0af5262af8f4807079

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...