TypeScript以安全的方式扩展本机对象,就像通过TS transformer扩展函数一样
TypeScript提供在编译期间转换AST的能力 我想知道它是否可以用于以安全的方式扩展本机对象、对象、数组和字符串,而不影响其原型 让我们将TypeScript以安全的方式扩展本机对象,就像通过TS transformer扩展函数一样,typescript,extension-methods,Typescript,Extension Methods,TypeScript提供在编译期间转换AST的能力 我想知道它是否可以用于以安全的方式扩展本机对象、对象、数组和字符串,而不影响其原型 让我们将isEmpty()方法添加到对象,数组,字符串等。首先,我们使用假声明欺骗TypeScript这样的方法存在: declare global { interface Object { isEmpty(): boolean } interface Array { isEmpty(): boolean } interfac
isEmpty()
方法添加到对象
,数组
,字符串
等。首先,我们使用假声明欺骗TypeScript这样的方法存在:
declare global {
interface Object {
isEmpty(): boolean
}
interface Array {
isEmpty(): boolean
}
interface String {
isEmpty(): boolean
}
}
然后我们编写AST transformer,它将转换我们在编辑器中键入的TS代码
{ a: 1 }.isEmpty()
[1, 2].isEmpty()
"hello".isEmpty()
在以下编译的JS代码中(我们全局公开NativeExtensions
,我们污染了全局范围,但只使用了一个变量)
而实施过程可能会更加复杂
NativeExtensions.isEmpty = (o) => {
if ('isEmpty' in o) return o.isEmpty()
if (o instanceof Array) return o.length == 0
if (typeof o == 'string' || o instanceof String) return o.length == 0
for (const k in o) if (o.hasOwnProperty(k)) return false
return true
}
您知道这是否可行,以及如何编写TS Transformer代码来实现这一点吗?也许在这方面已经做了一些努力?也许你可以通读这一期也许你可以通读这一期
NativeExtensions.isEmpty = (o) => {
if ('isEmpty' in o) return o.isEmpty()
if (o instanceof Array) return o.length == 0
if (typeof o == 'string' || o instanceof String) return o.length == 0
for (const k in o) if (o.hasOwnProperty(k)) return false
return true
}