npm install @types/jquery --save-dev
複製代碼
解釋: package.json 中有 types 字段,或者有一個 index.d.ts 聲明文件前端
/path/to/project
├── src
| └── index.ts
├── types
| └── foo
| └── index.d.ts
└── tsconfig.json
複製代碼
{
"compilerOptions": {
"module": "commonjs",
"baseUrl": "./",
"paths": {
"*": ["types/*"]
}
}
}
複製代碼
# let
declare let jQuery: (selector: string) => any;
# function
declare function jQuery(selector: string): any;
#class
declare class Animal {
name: string;
constructor(name: string);
sayHi(): string;
}
#enum
declare enum Directions {
Up,
Down,
Left,
Right
}
#namespace
declare namespace jQuery {
function ajax(url: string, settings?: any): void;
namespace fn {
function extend(object: any): void;
}
}
複製代碼
// types/foo/index.d.ts
export const name: string;
export function getName(): string;
export class Animal {
constructor(name: string);
sayHi(): string;
}
export enum Directions {
Up,
Down,
Left,
Right
}
export interface Options {
data: any;
}
export namespace foo {
const name: string;
namespace bar {
function baz(): string;
}
}
複製代碼
// types/foo/index.d.ts
# function、class 和 interface 能夠直接默認導出,其餘的變量須要先定義出來,再默認導出
export default function foo(): string;
export default Directions;
declare enum Directions {
Up,
Down,
Left,
Right
}
複製代碼
// types/foo/index.d.ts
declare const name: string;
declare function getName(): string;
declare class Animal {
constructor(name: string);
sayHi(): string;
}
declare enum Directions {
Up,
Down,
Left,
Right
}
#interface 前是不須要 declare
interface Options {
data: any;
}
export { name, getName, Animal, Directions, Options };
複製代碼
// types/foo-bar.d.ts
declare module 'foo' {
export interface Foo {
foo: string;
}
}
declare module 'bar' {
export function bar(): string;
}
// src/index.ts
import { Foo } from 'foo';
import * as bar from 'bar';
let f: Foo;
bar.bar();
複製代碼
// types/jquery-plugin/index.d.ts
/// <reference types="jquery" />
declare function foo(options: JQuery.AjaxSettings): string;
複製代碼
--declaration(簡寫 -d)
複製代碼
{
"compilerOptions": {
"module": "commonjs",
"outDir": "lib",
"declaration": true,
}
}
複製代碼
@types 是統一由 DefinitelyTyped 管理的。要將聲明文件發佈到 @types 下,就須要給 DefinitelyTyped 建立一個 pull-request,其中包含了類型聲明文件,測試代碼,以及 tsconfig.json 等。
複製代碼
本文做者: 前端漫談node
聯繫郵箱:simple2012hcz@126.comjquery