Skip to content

Commit

Permalink
feat: declare
Browse files Browse the repository at this point in the history
  • Loading branch information
AnsonZnl committed Sep 18, 2023
1 parent c4ca9d1 commit 2f6a08f
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions docs/articles/TypeScript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1416,6 +1416,25 @@ const cocoName = coco.greet();

上面示例中,greet()有两个装饰器,内层的@log 先执行,外层的@bound 针对得到的结果再执行。

## declare 关键字

declare 关键字用来告诉编译器,某个类型是存在的,可以在当前文件中使用。

它的主要作用,就是让当前文件可以使用其他文件声明的类型。举例来说,自己的脚本使用外部库定义的函数,编译器会因为不知道外部函数的类型定义而报错,这时就可以在自己的脚本里面使用 `declare` 关键字,告诉编译器外部函数的类型。这样的话,编译单个脚本就不会因为使用了外部类型而报错。

declare 关键字可以描述以下类型。

- 变量(const、let、var 命令声明)
- type 或者 interface 命令声明的类型
- class
- enum
- 函数(function)
- 模块(module)
- 命名空间(namespace)
- declare 关键字的重要特点是,它只是通知编译器某个类型是存在的,不用给出具体实现。比如,只描述函数的类型,不给出函数的实现,如果不使用 declare,这是做不到的。

declare 只能用来描述已经存在的变量和数据结构,不能用来声明新的变量和数据结构。另外,所有 declare 语句都不会出现在编译后的文件里面。

## 其他

### 定义 window
Expand Down

1 comment on commit 2f6a08f

@vercel
Copy link

@vercel vercel bot commented on 2f6a08f Sep 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

v-blog – ./

zhangningle.vercel.app
v-blog-znl-github.vercel.app
v-blog-git-master-znl-github.vercel.app

Please sign in to comment.