简体   繁体   English

Typescript 联合类型泛型参数

[英]Typescript union type generic parameter

So I have the following code sample:所以我有以下代码示例:

interface MyInterface<T> {
  myFunc(value: T): void;
}

class MyImplementation implements MyInterface<number> {
  myFunc(value: number): void {
    console.log(value / 2);
  }
}

function myTest(): MyInterface<number|string> {
  return new MyImplementation(); // doesn't look quite right
}

myTest().myFunc("I am not a number"); // outputs NaN

I can't quite get my head around why typescript is allowing me to return MyImplementation in place of MyInterface<number |我不太明白为什么 typescript 允许我返回MyImplementation代替MyInterface<number | string> .字符串> I understand we want number to be assignable to number |我知道我们希望number可以分配给number | string but surely not for generic parameters.字符串,但肯定不适用于泛型参数。

This example also works without generics:此示例在没有 generics 的情况下也适用:

interface MyInterface {
  myFunc(value: number): void;
}

interface MyInterface2 {
  myFunc(value: number|string): void;
}

class MyImplementation implements MyInterface {
  myFunc(value: number): void {
    console.log(value / 2);
  }
}

function myTest(): MyInterface2 {
  return new MyImplementation(); // doesn't look quite right
}

myTest().myFunc("I am not a number"); // outputs NaN

Typescript was designed to have some unsoundness in the type system as described here: https://www.typescriptlang.org/docs/handbook/type-compatibility.html Typescript 被设计为在类型系统中存在一些不健全,如下所述: https://www.typescriptlang.org/docs/handbook/type-compatibility.ZFC35FDC70D5FC69D2693EZ5A

To work around this, you can define your interface like this:要解决此问题,您可以像这样定义您的界面:

interface MyInterface<T> {
  myFunc: (value: T) => void;
}

And then enable strictFunctionTypes or strict in your tsconfig.json .然后在您的tsconfig.json中启用strictFunctionTypesstrict

See also: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-6.html另见: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-6.html

The stricter checking applies to all function types, except those originating in method or constructor declarations.更严格的检查适用于所有 function 类型,但源自方法或构造函数声明的类型除外。 Methods are excluded specifically to ensure generic classes and interfaces (such as Array) continue to mostly relate covariantly.专门排除方法以确保泛型类和接口(例如 Array)继续主要以协变方式相关。

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

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