gpt4 book ai didi

typescript - 如何向现有类型添加静态方法?

转载 作者:搜寻专家 更新时间:2023-10-30 21:09:21 25 4
gpt4 key购买 nike

例如,我想给RegExp类型添加一个静态的quote方法:

RegExp.quote = (text: String) => { ... };

但是当我尝试这样做时,我收到以下错误:

The property 'quote' does not exist on value of type '{ $1: string; $2: string; $3: string; $4: string; $5: string; $6: string; $7: string; $8: string; $9: string; lastMatch: string; (pattern: string, flags?: string): RegExp; new(pattern: string, flags?: string): RegExp; }'.

最佳答案

恐怕只有这个丑陋的解决方案:

// add it 
RegExp['quote'] = (whatev:any):any => { return whatev;};

// Use it
RegExp['quote']('asdf');

// The default behaviour is intact:
var foo = new RegExp('/asdf/');

我认为模块会允许它工作,但我已经证实它不会。

参见:https://stackoverflow.com/a/16824687/390330和一个功能请求:https://typescript.codeplex.com/workitem/917

关于typescript - 如何向现有类型添加静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18427016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com