ts 中的declare 具体用法

image.png

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

阅读 22.4k
2 个回答

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...

declare就是告诉TS编译器你担保这些变量和模块存在,并声明了相应类型,编译的时候不需要提示错误

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题