ts declare使用
时间: 2023-07-11 22:32:44 浏览: 124
In TypeScript, the `declare` keyword is used to tell the compiler that a variable, function, class, or namespace already exists and is defined elsewhere. This is useful when you want to use a library or framework that was written in JavaScript, but you want to write your code in TypeScript.
Here are a few examples of how to use `declare` in TypeScript:
1. Declare a global variable:
```
declare const myVar: string;
```
This tells TypeScript that `myVar` is a global variable of type `string`, but the variable is not defined in the current file.
2. Declare a function:
```
declare function myFunc(param: string): number;
```
This tells TypeScript that `myFunc` is a function that takes a parameter of type `string` and returns a value of type `number`, but the function is not defined in the current file.
3. Declare a class:
```
declare class MyClass {
constructor(param: string);
myMethod(): void;
}
```
This tells TypeScript that `MyClass` is a class with a constructor that takes a parameter of type `string`, and the class has a method called `myMethod` that returns `void`, but the class is not defined in the current file.
4. Declare a namespace:
```
declare namespace MyNamespace {
const myVar: string;
function myFunc(param: string): number;
class MyClass {
constructor(param: string);
myMethod(): void;
}
}
```
This tells TypeScript that `MyNamespace` is a namespace that contains a variable called `myVar`, a function called `myFunc`, and a class called `MyClass`, but the namespace is not defined in the current file.
Using `declare` in TypeScript is a powerful tool for working with existing JavaScript code and libraries.
阅读全文