class ts 扩展方法_ts类型声明文件的正确使用姿势
ts類型聲明文件的正確使用姿勢
ts聲明文件類型
npm install @types/jquery --save-dev
與npm一同發布
解釋: package.json 中有 types 字段,或者有一個 index.d.ts 聲明文件
自給自足型
創建一個 node_modules/@types/foo/index.d.ts 文件,存放 foo 模塊的聲明文件。不太建議用這種方案,一般只用作臨時測試。
創建一個 types 目錄,專門用來管理自己寫的聲明文件,將 foo 的聲明文件放到 types/foo/index.d.ts 中。這種方式需要配置下 tsconfig.json 中的 paths 和 baseUrl 字段。
/path/to/project
├── src
| └── index.ts
├── types
| └── foo
| └── index.d.ts
└── tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"baseUrl": "./",
"paths": {
"*": ["types/*"]
}
}
}
ts聲明文件書寫姿勢
全局型
# 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;
}
}
npm包型 - export
// 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;
}
}
npm包型 - export default
// types/foo/index.d.ts
# function、class 和 interface 可以直接默認導出,其他的變量需要先定義出來,再默認導出
export default function foo(): string;
export default Directions;
declare enum Directions {
Up,
Down,
Left,
Right
}
npm包型 - 先聲明,在export
// 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 };
module 拓展
// 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
///
declare function foo(options: JQuery.AjaxSettings): string;
ts文件tsc自動生成聲明文件
命令行參數
--declaration(簡寫 -d)
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"outDir": "lib",
"declaration": true,
}
}
ts發布
發布到社區
@types 是統一由 DefinitelyTyped 管理的。要將聲明文件發布到 @types 下,就需要給 DefinitelyTyped 創建一個 pull-request,其中包含了類型聲明文件,測試代碼,以及 tsconfig.json 等。
與源碼一起(依次查找*.d.ts)1. 給 package.json 中的 types 或 typings 字段指定一個類型聲明文件地址
2. 在項目根目錄下,編寫一個 index.d.ts 文件
3. 針對入口文件(package.json 中的 main 字段指定的入口文件),編寫一個同名不同后綴的 .d.ts 文件
參考
歡迎關注我們【前端漫漫】,了解最新文章動態!聯系郵箱:simple2012hcz@126.com
總結
以上是生活随笔為你收集整理的class ts 扩展方法_ts类型声明文件的正确使用姿势的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 英特尔AMD竞相为笔记本处理器添加图形功
- 下一篇: 用VC写Assembly代码(5) --