简体   繁体   English

基本类型字符串上的TypeScript重载方法

[英]TypeScript overloading method on base-type string

TypeScript-Version: 1.6 TypeScript版本:1.6

I'm trying to add another overload-function for String s replace -function which should have the following signature: 我正在尝试为Stringreplace -function添加另一个重载函数,该函数应具有以下签名:

replace(searchValue: string, replaceValue: any): string;

So it can be used like 所以它可以像

"someString".replace("replaceMe", $(evt.target).data("row-id"))

I need any as of .data is defined as: 我需要any .data定义为:

data(key: string): any;

My String.d.ts (declaration) 我的String.d.ts (声明)

interface String {
    /**
      * Replaces text in a string, using a regular expression or search string.
      * @param searchValue A string that represents the regular expression.
      * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.
      */
    replace(searchValue: string, replaceValue: any): string;
}

My String.ts (implementation) 我的String.ts (实现)

String.prototype.replace = (searchValue: string, replaceValue: any):string =>
{
    if (replaceValue instanceof String) {
        var stringReplacement = replaceValue.toString();
        return String.prototype.replace(stringReplacement, replaceValue);
    } else {
        return replaceValue;
    }
}

The following error is thrown and I'm not sure why and how it can be fixed: 引发以下错误,但我不确定为什么以及如何解决该错误:

Error TS2322 Type '(searchValue: string, replaceValue: any) => string' is not assignable to type '{ (searchValue: string, replaceValue: string): string; 错误TS2322类型'((searchValue:字符串,replaceValue:任意)=>字符串)无法分配给类型'{{(searchValue:字符串,replaceValue:字符串):字符串; (searchValue: string, replacer: (substring...'. Types of parameters 'searchValue' and 'searchValue' are incompatible. Type 'string' is not assignable to type 'RegExp'. Property 'exec' is missing in type 'String'. (searchValue:字符串,replacer :(子字符串...”。参数“ searchValue”和“ searchValue”的类型不兼容。类型“ string”不可分配给“ RegExp”类型。类型“ String”中缺少属性“ exec” '。

Edit #1 编辑#1

I ended up with just the declaration for replace (and removement of the implementation) to satisfy the compiler: 最后,我只声明了replace (和删除实现)来满足编译器的要求:

interface String {
    /**
      * Replaces text in a string, using a regular expression or search string.
      * @param searchValue A string that represents the regular expression.
      * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.
      */
    replace(searchValue: string, replaceValue: any): string;
}

Is this still wrong as of internally it still calls the replace -function of the library? 从内部来看,这仍然是错误的,它仍然调用库的replace function吗?

Edit #2 编辑#2

If using nothing own Visual Studio is yelling 如果不使用自己的Visual Studio大喊大叫

枯萎

With cast it shows (ReSharper) 使用演员表显示(ReSharper)

ReSharper说

With example 4.1 (MartyIX) 带有示例4.1(MartyIX)

带有变量声明

Doing "someString".replace("replaceMe", $(evt.target).data("row-id")); 进行"someString".replace("replaceMe", $(evt.target).data("row-id")); should work because any can be assigned to string . 应该可以工作,因为可以将any分配给string I'm not sure why you're getting an error, but I would recommend making sure the function signatures with string as the first parameter for replace haven't been removed from lib.d.ts . 我不确定为什么会出错,但是我建议确保尚未从lib.d.ts删除具有string作为replace第一个参数的函数签名。 You can double check that by going to the definition of replace (put cursor on replace and hit F12) and making sure it has all the function signatures shown below. 您可以通过转到replace的定义(将光标放在replace上并单击F12)并确保它具有下面显示的所有功能签名来再次检查。 You can also try disabling resharper temporarily to see if that makes the error go away. 您也可以尝试暂时禁用重新共享器,以查看该错误是否消失。

By the way, to fix your error with overriding String.prototype.replace , it already has these possible function signatures: 顺便说一下,要通过覆盖String.prototype.replace来修复错误,它已经具有以下可能的函数签名:

replace(searchValue: string, replaceValue: string): string;
replace(searchValue: string, replacer: (substring: string, ...args: any[]) => string): string;
replace(searchValue: RegExp, replaceValue: string): string;
replace(searchValue: RegExp, replacer: (substring: string, ...args: any[]) => string): string;

What was written is not compatible when searchValue is a RegExp , so you need to change the function signature to allow both string and RegExp by using a union type: searchValueRegExp ,编写的内容不兼容,因此您需要使用联合类型来更改函数签名以同时允许stringRegExp

String.prototype.replace = function(searchValue: string | RegExp, replaceValue: any) {
    // omitted
}

I'm not sure what you're trying to do though because the function will do an infinite loop. 我不确定您要做什么,因为该函数将执行无限循环。 Maybe you meant to hold a reference to the original String.prototype.replace and call that? 也许您打算保留对原始String.prototype.replace的引用并调用它? Remember that when you assign to String.prototype.replace you overwrite the original function. 请记住,当您分配给String.prototype.replace时,您将覆盖原始函数。

Overall though don't do what's being done here . 总的来说,尽管不做这里正在做的事情 Look up "don't modify objects you don't own" to see what I mean. 查找“不要修改您不拥有的对象”以了解我的意思。 It would be better if you create your own separate function to do this because right now this replace function breaks any code that uses it . 如果创建自己的单独函数来执行此操作会更好,因为现在此replace函数会破坏使用该函数的所有代码 You'll get really weird behaviour if any library you use uses the replace method and it will be difficult to trace the problem. 如果您使用的任何库都使用replace方法,那么您将获得真正的怪异行为,这将很难跟踪问题。

My take on this: 我对此:

1) The following piece of code does not report any errors on my machine: 1)以下代码段未报告我的计算机上的任何错误:

/// <reference path="typings/jquery/jquery.d.ts" />

"someString".replace("replaceMe", $('#test').data("row-id"));

Are you sure that there is an issue in the first place? 您确定首先存在问题吗? What is your setting for the TypeScript compiler (ie how do you compile TS code)? 您对TypeScript编译器的设置是什么(即,如何编译TS代码)?

2) If you need to implement a replace method, you should really consider to create your own module for that otherwise you may cause great confusion for people who read your code: 2)如果需要实现replace方法,则应真正考虑为此创建自己的模块,否则可能会使阅读代码的人感到困惑:

module Project.Utils {
    export class String {   
        public replace = (searchValue: string, replaceValue: any):string =>
        {
            // some replace implementation
        }
    }
}

3)The implementation is wrong in the first place because you replace String.prototype.replace and then you expect that it will call the native implementation of String.prototype.replace and that is not true. 3)首先,实现是错误的,因为您替换了String.prototype.replace ,然后希望它会调用String.prototype.replace的本机实现,但这不是正确的。 Effectively your implementation does NOT do any replacing functionality at all. 实际上,您的实现根本不执行任何替换功能。

String.prototype.replace = (searchValue: string, replaceValue: any):string =>
{
    if (replaceValue instanceof String) {
        var stringReplacement = replaceValue.toString();
        return String.prototype.replace(stringReplacement, replaceValue);
    } else {
        return replaceValue;
    }
}

4) This codes run perfectly fine in http://www.typescriptlang.org/Playground : 4)这些代码在http://www.typescriptlang.org/Playground上运行得很好:

let n:any = 1; 
"someString".replace("replaceMe", n); 

"someString".replace("replaceMe", <any>5); // explicit cast

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用不同类型(非原始)的一个参数重载的Typescript方法 - Typescript method overloading with one parameter of different type (non-primitive) 有没有办法在 TypeScript 中进行方法重载? - Is there a way to do method overloading in TypeScript? 使用“异步”操作重载打字稿方法 - Typescript method overloading using "async" operation 打字稿:与基本类型平行的自定义类型被忽略 - Typescript: Custom type that parallels base type ignored typescript 字符串或自定义类型 - typescript string or custom type React Typescript 泛型类型重载(例如 useState) - React Typescript Generic Type Overloading (e.g. useState) 在 Get 方法中使用 String Literal 的 Base Constructor 中的 TypeScript 派生类属性 - TypeScript Derived Class Properties in Base Constructor using String Literal in Get Method Can Typescript可以推断出由其基类方法实例化的扩展类实例的类型吗? - Can Typescript infer the type of an instance of an extension class instantiated by a method of its base? Typescript根据if语句自动判断出什么类型 - Typescript automatically figure what is the type base on the if statement 无法在基类打字稿上调用扩展方法 - Cannot call extension method on base class typescript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM