繁体   English   中英

TypeScript:实现接口时是否需要参数类型?

[英]TypeScript: Are argument types needed when implementing an interface?

假设我有以下接口IFace和接口Add的实现:

interface IFace {
    add(a: number, b:number): number
}

class Add implements IFace {
   add(a,b)
}

在我的Add类中实现add()方法时,是否可以不指定:

  1. 方法的返回类型?
  2. 参数ab的类型?

我尝试在 Stack Overflow 上搜索,但互联网没有找到任何相关内容。

根据打字稿语法要求,必须在Add classes add()函数的方法签名中指定每个参数的类型。 然而,您的Addadd()函数的返回类型可以从正在实现的接口中推断出来,并且不需要显式提供。

因此,以下内容是有效的:

interface IFace {
    add(a: number, b:number): number
}

class Add implements IFace {

 /* Must supply number types for a and b, but return type of function be be omitted */
 add(a:number,b:number) {
    return a + b;
 }
}

从官方打字稿文档 ( https://www.typescriptlang.org/docs/handbook/interfaces.html ) 开始,接口描述了类的公共端,而不是公共端和私有端。 这禁止您使用它们来检查类是否也具有用于类实例的私有端的特定类型(所以是的,在这种情况下,您需要定义 a & b 和 d 的类型)

interface ClockInterface {
    currentTime: Date;
    setTime(d: Date): void;
}

class Clock implements ClockInterface {
    currentTime: Date = new Date();
    setTime(d: Date) {
        this.currentTime = d;
    }
    constructor(h: number, m: number) { }
}

暂无
暂无

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

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