简体   繁体   English

Angular,将泛型类型传递给另一个函数。 如何输入参数?

[英]Angular, pass generic type into another function. How to typed param?

I have function like:我有这样的功能:

getSomething<T>(value: T): any{
    const temp = this.doSomething<T>(value);
...
}

doSomething<T>(value: T): any {
    return value.replace(/\s/g, '');
}

Initially the value passed has a type specific type T, I know full well that in the final function it will be a string.最初传递的值具有特定于类型的类型 T,我很清楚在最终函数中它将是一个字符串。 However, doing it this way I can't use replace function.但是,这样做我不能使用替换功能。 Help.帮助。

You need to say that value would have string methods.您需要说该值将具有字符串方法。 Like this:像这样:

getSomething<T extends string>(value: T): any{
    const temp = this.doSomething<T>(value);
...
}

doSomething<T extends string>(value: T): any {
    return value.replace(/\s/g, '');
}

Think about your problem in the following way:请按以下方式思考您的问题:

  1. How can I be sure that provided type has "replace()" method?如何确定提供的类型具有“replace()”方法?
  2. What would happen if I provide different type eg number or null?如果我提供不同的类型,例如 number 或 null,会发生什么?

You have to somehow tell Typescript that you expect to get an argument that has method "replace()".你必须以某种方式告诉 Typescript 你希望得到一个具有方法“replace()”的参数。 You can do it by creating additional interface and mention that generic type extends that interface:您可以通过创建附加接口并提及泛型类型扩展该接口来实现:

interface Replacable {
  replace: (regexp: RegExp, str: string) => string
}

function getSomething<T extends Replacable>(value: T): any{
    const temp = doSomething<T>(value);
    console.log(temp);
}

function doSomething<T  extends Replacable>(value: T): any {
    return value.replace(/\s/g, '');
}

Read more about Generic Constraints here: https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints在此处阅读有关通用约束的更多信息: https : //www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM