美文网首页
2020-11-18 在ts中使用js (.d.ts写法)

2020-11-18 在ts中使用js (.d.ts写法)

作者: FConfidence | 来源:发表于2020-11-18 15:09 被阅读0次

ts中使用js

  1. util.js

    export functionName(value) {
      return value;
    }
    
    export default {
      functionName
    }
    
  2. util.d.ts

    interface IDefaultExports {
      functionName: (arg?: string): string;
    }
    
    export function functionName(value?: string): string;
    
    declare const defaultExports: IDefaultExports;
    
    export default IDefaultExports;
    
    // src/Animal.d.ts
    declare class Animal {
        name: string;
        constructor(name: string);
        sayHi(): string;
    }
    declare enum Directions {
        Up,
        Down,
        Left,
        Right
    }
    
  3. 针对esm模块

    (function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
    (global.WeCropper = factory());
    }(this, (function () { 'use strict';})
    
    declare const WeCropper: any;
    export default WeCropper;
    

举例

  1. 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;
}


// src/index.ts

import { name, getName, Animal, Directions, Options } from 'foo';

console.log(name);
let myName = getName();
let cat = new Animal('Tom');
let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];
let options: Options = {
    data: {
        name: 'foo'
    }
};
  1. 混用declare和const
// 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 Options {
    data: any;
}

export { name, getName, Animal, Directions, Options };

相关文章

网友评论

      本文标题:2020-11-18 在ts中使用js (.d.ts写法)

      本文链接:https://www.haomeiwen.com/subject/hpeciktx.html