账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    如何在Typescript中添加Polyfill?
    30
    0

    Typescript在编译时只会将typescript的语法编译为ES6/ES5的语法,而并不会将对象上的方法(如Object.assign)进行编译,或自动添加polyfill。
    而现在浏览器的原因,我们必须要把Object.assign这类ES6的语法转化成ES5,或添加polyfill,如何解决?

    编译前

    const obj = (<any>Object).assign({},{a:1,b:2})
    
    const aaa = (aaa: number) => aaa * 2;

    编译后

    var obj = Object.assign({}, { a: 1, b: 2 });
    var aaa = function (aaa) { return aaa * 2; };

    可见Object.assign并没有被转化。
    如何解决?

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 在TypeScript中添加Polyfill主要是通过在类型系统中使用TypeScript的接口和泛型来实现。具体步骤如下:

      1. 首先,你需要创建一个类型声明文件,这个文件定义了你想要Polyfill支持的类型。

      typescript export interface MyPolyfill { // your implementation here }

      1. 在类型声明文件中,你需要声明一个类型工厂接口,这个接口定义了你如何创建你的Polyfill实例。

      typescript export interface TypeFactory { create<T>(myInterface: MyPolyfill): T; }

      1. 在你的类型系统中,你需要使用TypeScript的接口和泛型来实现你的Polyfill。例如,你可以创建一个类型工厂接口,并使用它来创建你的Polyfill实例。

      ```typescript import { TypeFactory } from './type-factory';

      interface MyPolyfill { // your implementation here }

      export class MyPolyfillFactory implements TypeFactory { create(myInterface: MyPolyfill): T { // your implementation here } }

      export function myMethod(myInterface: MyPolyfill): T { // your implementation here return myInterface; } ```

      1. 最后,你可以使用你的TypeFactory来创建你的Polyfill实例。

      typescript const myPolyfill = new MyPolyfillFactory(); const result = myPolyfill.create<MyPolyfill>(myInterface);

      这样,你就可以在TypeScript中添加Polyfill了。

    更多回答
    网站公告
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部