Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

ts 中的declare 具体用法

image.png

如图,index.ts 中只能导入D4 那为什么在 右侧的申明文件中 namespace 变量 函数 前使用 declare 有什么用


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

declare module xxx {} 是用来做一些第三方库没有支持ts的,通过declare module,让我们在代码中可以import进来,从而使用它

一般来说这个 .d.ts 文件会被放在工程的更目录下,如:

xxx.d.ts

declare module "test" {
  export var value: number;
  export function hello(str: string): String;
}

declare var D2: string;

declare namespace mySpace {
  interface ITest {
    id: number;
  }
}

这样子我们在文件中 import 那个没有支持ts的库就不会报错了,而且还会提示 库暴露出来的属性/方法

import test from "test";

test.hello('123');
test.value;

window.D2 = "hello";

const obj: mySpace.ITest = {
  id: 1
};

上面的例子只有 declare module 才是定义一个模块,才能被 import,其他的用法如上

之前有写过一篇文章,有粗略讲了.d.ts,感兴趣可以看看哦~
https://mp.weixin.qq.com/s/L0...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...