Skip to content

TypeScript项目中使用类型声明 #52

Description

@webplus

一、公共库类型声明

比如echarts、lodash
这类库文件的声明文件可以安装获取,npm install --save @types/lodash @types/echarts

配置 tsconfig.json 的 compilerOptions.types 选项,引入有意义的类型:

{
  "compilerOptions": {
    "types" : [
      "jquery",
      "echarts",
      "lodash"
    ]
  }
}

使用时可以直接导入类型

import { EChartOption, ECharts } from 'echarts';

参考

二、项目类型声明

  • 全局类型声明,使用时不需要在import
// global.d.ts 
// 注意这个文件里不要出现 export import等模块语法,否则会被当作module声明而非全局
interface HTMLElement {
  webkitRequestFullscreen(options?: FullscreenOptions): Promise<void>;
  webkitRequestFullScreen(options?: FullscreenOptions): Promise<void>;
  msRequestFullscreen(options?: FullscreenOptions): Promise<void>;
  mozRequestFullScreen(options?: FullscreenOptions): Promise<void>;

  onwebkitfullscreenchange: ((this: Element, ev: Event) => any) | null;
  onmozfullscreenchange: ((this: Element, ev: Event) => any) | null;
  MSFullscreenChange: ((this: Element, ev: Event) => any) | null;
}

interface Document {
  readonly webkitFullscreenElement: Element | null;
  readonly msFullscreenElement: Element | null;
  readonly mozFullScreenElement: Element | null;

  webkitExitFullscreen(): Promise<void>;
  msExitFullscreen(): Promise<void>;
  mozCancelFullScreen(): Promise<void>;
}
// window对象
interface Window {
  // vue根实例对象
  __app__: any;
}

interface WheelEvent {
  path?: EventTarget[];
}

declare function parseInt(s: string | number, radix?: number): number;
declare function parseFloat(string: string | number): number;

declare type Dictionary<T> = Record<string, T>;
  • 模块类型文件,
    使用时
    import { ScrollContainer, ScrollContainerOptions } from '@/components/container/index';
// index.ts 模块整体导出
export { default as ScrollContainer } from './src/ScrollContainer.vue';
export { default as CollapseContainer } from './src/CollapseContainer.vue';
export { default as LazyContainer } from './src/LazyContainer.vue';

export * from './types';
// types.ts  类型定义
export type ScrollType = 'default' | 'main';

export enum TypeEnum {
  DEFAULT = 'default',
  MAIN = 'main',
}
export interface CollapseContainerOptions {
  canExpand?: boolean;
  title?: string;
  helpMessage?: Array<any> | string;
}
export interface ScrollContainerOptions {
  enableScroll?: boolean;
  type?: ScrollType;
}

.d.ts的编写方式

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions