简体   繁体   English

为什么 TypeScript 不强制接口签名?

[英]Why TypeScript doesn't enforce interface signature?

So, I've the following interface:所以,我有以下界面:

interface DoStuffInterface {
    doStuff(value: string | number): string | number;
}

Why when implementing this interface TS doesn't enforce the signature?为什么在实现这个接口时 TS 不强制签名?

class NumberStuff implements DoStuffInterface {
    public doStuff(value: number): string | number { // <====== missing: | string
        return value;
    }
}

class StringStuff implements DoStuffInterface {
    public doStuff(value: string): string | number { // <====== missing: | number
        return value.toLowerCase();
    }
}

This is easily breakable with something like this:这很容易被破坏:

var numberStuff = new NumberStuff();
var stringStuff = new StringStuff();

function run(thing: DoStuffInterface): void {
    console.log(thing.doStuff(42));
}

run(numberStuff);
run(stringStuff); // <====== this fails, due to: `42.toLowerCase()`

So, why TS doesn't enforce NumberStuff & StringStuff to have the proper signature?那么,为什么 TS 不强制NumberStuffStringStuff具有正确的签名? If the signature was properly set this would be a compile-time error, instead you get a run-time error.如果签名被正确设置,这将是一个编译时错误,而不是你得到一个运行时错误。

Am I missing some config flag?我错过了一些配置标志吗? Or is it expected behaviour?或者这是预期的行为?

Here the full example 这里是完整的例子

TLDR to enable the desired behavior change method to property: TLDR 启用所需的行为更改方法到属性:

interface DoStuffInterface {
    doStuff: (value: string | number) => string | number;
}

Playground 操场


For interfaces under strictFunctionTypes function type parameter positions are checked contravariantly (for "function prop") instead of bivariantly (for method)对于strictFunctionTypes下的接口,函数类型参数位置被逆变检查(对于“函数道具”)而不是双变(对于方法)

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

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

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