# 参考

如何写出高质量的定义文件

# 具有属性的对象

假设一个对象,具有一个方法和一个属性

let result = myLib.makeGreeting("hello, world");
console.log("The computed greeting is:" + result);
let count = myLib.numberOfGreetings;

声明文件

declare namespace myLib {
  function makeGreeting(s: string): string;
  let numberOfGreetings: number;
}

在这里我们只需要将 myLib 当做一个 namespace 就可以了。

# 函数重载

let x: Widget = getWidget(43);
let arr: Widget[] = getWidget("all of them");

定义重载

declare function getWidget(n: number): Widget;
declare function getWidget(s: string): Widget[];

# 可重用类型(interface)

greet({
  greeting: "hello world",
  duration: 4000,
});

使用 interface

interface GreetingSettings {
  greeting: string;
  duration?: number;
  color?: string;
}
declare function greet(setting: GreetingSettings): void;

# 可重用类型(type 别名)

function getGreeting() {
  return "howdy";
}
class MyGreeter extends Greeter {}
greet("hello");
greet(getGreeting);
greet(new MyGreeter());

使用 type 的联合类型

type GreetingLike = string | (() => string) | MyGreeter;
declare function greet(g: GreetingLike): void;

# 组织类型

代码

const g = new Greeter("Hello");
g.log({ verbose: true });
g.alert({ modal: false, title: "Current Greeting" });

声明

declare namespace GreetingLib {
  interface LogOptions {
    verbose?: boolean;
  }
  interface AlertOptions {
    modal: boolean;
    title?: string;
    color?: string;
  }
}

#

代码

const myGreeter = new Greeter("hello, world");
myGreeter.greeting = "howdy";
myGreeter.showGreeting();
class SpecialGreeter extends Greeter {
  constructor() {
    super("Very special greetings");
  }
}

声明

declare class Greeter {
  constructor(greeting: string);
  greeting: string;
  showGreeting(): void;
}

# 全局变量

代码

console.log("Half the number of widgets is " + foo / 2);

声明

declare var foo: number;

# 全局函数

代码

greet("hello, world");

声明

declare function greet(greeting: string): void;