鸿则_
鸿则_

Reputation: 342

Why the variable type becomes any?

Update 1:

mxGraph.d.ts full code:

declare module 'mxgraph' {

  class mxGraph {

    constructor(container: HTMLElement);
  
  }
}

index.d.ts full code:

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

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

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

I am create a type declaration library for mxgraph package, primary code is:

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

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

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

When I use in my project, all property type is any under mx namespace:

import mxgraphFactory from 'mxgraph';

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

mx.mxGraph;

enter image description here


Type of mx is valid.

enter image description here


Upvotes: 0

Views: 426

Answers (2)

鸿则_
鸿则_

Reputation: 342

After trying, I found out why, index.d.ts should use /// <reference path="..." /> to reference other declaration files. this commit fix the issues https://github.com/typed-mxgraph/typed-mxgraph/commit/244b0124ae46d09793f4cb0af5262af8f4807079

Upvotes: 0

glinda93
glinda93

Reputation: 8459

Why the variable type becomes any?

You shouldn't have used typeof operator. typeof returns the type of value, thus it can be anything.

Consider this example:

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

Here foobar.foo is of any type and it is still valid in typescript. Although typeof was not meant to be used like that.

enter image description here

Solution:

Define MxGraph type first and

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

Upvotes: 1

Related Questions