TypeScript 接口实现不检查方法参数 [英] TypeScript interface implementing doesn't check method parameters

查看:37
本文介绍了TypeScript 接口实现不检查方法参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

interface IConverter {
    convert(value: number): string
}

class Converter implements IConverter {
    convert(): string { // no error?
        return '';
    }
}

const v1: IConverter = new Converter();
const v2: Converter = new Converter();

v1.convert(); // error, convert has parameter, although Converter's convert doesn't expect one
v2.convert(); // ok, convert has no parameters, although Converter implements IConverter which should has paramater

Converter 实现了IConverter,它有一个带一个参数的方法,但是Converter 缺少这个参数.如果我们没有完全实现这个接口,为什么 TS 编译器不会引发错误?

Converter implements IConverter, which has a method with one parameter, but Converter lacks this parameter. Why TS compiler doesn't raise an error if we do not fully implements this interface?

推荐答案

Typescript 使用结构化类型来确定类型兼容性.对于函数,这意味着声明和实现不需要完全相同的签名,只要编译器可以确定通过声明调用实现是安全的.

Typescript uses structural typing to determine type compatibility. For functions this means that you don't need to have the exact same signature for the declaration and the implementation, as long as the compiler can determine the implementation to be safe to call through the declaration.

在这种情况下,这归结为,参数较少的函数可以是具有较多参数的函数声明的实现,因为实现会忽略传入的额外参数,因此不会因此发生运行时错误(无论如何,在大多数情况下,可能存在依赖于 Function.length)

In this case this boils down to, a function with less parameters can be an implementation for a function declaration with more parameters as the extra passed in parameters will be ignored by the implementation, so no runtime error can occur because of this (for the most cases anyway, there might be corner cases on things that depend on Function.length)

你在 v1 上得到错误而不是在 v2 上得到错误的原因是因为一旦赋值完成,编译器只知道变量的类型而不是你最初赋值的它并将根据变量的实际类型进行检查.所以对于 v1 这意味着 IConverter.convert 需要一个参数,没有办法知道它不需要.对于 v2 它将检查 Converter.convert 已知不需要参数.

The reason you get an error on v1 but not v2 is because once the assignment is done the compiler only knows the type of the variable not what you originally assigned into it and will check based on the actual type of the variable. So for v1 this means IConverter.convert requires a parameter, no way to know it does not. For v2 it will check Converter.convert which is known to require no arguments.

这篇关于TypeScript 接口实现不检查方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆