在不支持 ES5 的浏览器中,打字稿装饰器的以下功能是否会被填充

Will the following features of typescript decorators get polyfilled in browsers that don't support ES5

typescript documentation 中警告:

NOTE  The Property Descriptor will be undefined if your script target is less than ES5.

If the method decorator returns a value, it will be used as the Property Descriptor for the method.

NOTE  The return value is ignored if your script target is less than ES5.

因此,如果您想使用上述装饰器的功能,我不清楚这对不支持 ES-5 构建的低端浏览器意味着什么。

警告提示的两种情况中哪一种是正确的。

a) 如果您使用的是支持编译为 ES5 的 Angular/TS 版本,那么您就可以了。无论您是否使用这些功能,所有浏览器都可以正常工作

b) 即使您的 angular 项目确实支持编译为 ES5,那么为早期浏览器(例如 main-es2015)制作的 slug 将不支持上述功能。即在使用它们时要非常小心。

我不能对 angular 给予任何保证,但我可以保证装饰器在旧浏览器中仍然可以正常工作。

装饰器作为一个函数,以 class / 方法作为参数调用,在旧版浏览器上仍然可以正常工作。例如,如果我有一个装饰器来简单地 Object.freeze() 我的 class 那很好:


@Object.freeze
class Test {
}
Test.a = 5;

此代码应该会在 supports Object.freeze 是否支持 属性 描述符的任何浏览器上正确抛出错误。 (这是一个非常薄弱的​​例子,因为描述符比 freeze 早,但重点仍然存在。)

但是访问器属性是 supported as long as Object.defineProperty is supported

function nonWritable(target: any,propertyKey: string | symbol,descriptor?: PropertyDescriptor): any{
    return {
        ...descriptor,
        writable: false
    }
}

class Test {
    @nonWritable
    field = 10;
}

const x = new Test();
x.field = 11;

这只会在支持描述符的浏览器中抛出 Attempted to assign to readonly property. 错误,较旧的浏览器仍会调用描述符,但第三个参数 descriptor 将是 undefined 并且装饰器的 return 值(新描述符)被忽略。

这意味着可以编译为 ES5 的 angular 版本肯定会起作用,因为这意味着装饰器绝对不依赖于描述符行为。 Angular 编译到较新版本不一定 保证 仍然可以在旧浏览器上工作,但我怀疑描述符是兼容性的限制因素,唯一真正不是的因素向后兼容是 getter/setters 并且它们对应于 API 差异所以我 猜测 你在装饰器前面是安全的。