2

我有以下接口:

interface Ixy 
{
    X: string;
    Y: string;
}
interface Ixz 
{
    X: string;
    Z: string;
}

这个功能:

export function update(json: Ixy) {
    var a = json.X;
}

从以下两个地方调用该函数:

export function update1(json: Ixy) {
   update(json);
}
export function update2(json: Ixz) {
   update(json);
}

有人可以向我解释我可以使用打字稿进行这项工作的最佳方式吗?现在 update1 没问题,但 update2 显示签名不匹配。是我可以解决此问题以将 json 的类型更改为任何类型的唯一方法,还是有更好的方法来做到这一点?

4

1 回答 1

1

有几种方法可以做到这一点。可能最好的方法是创建一个Ixx具有 common 属性的基本接口X,然后将其扩展为 create Ixyand Ixz,然后实现updatewithIxx作为参数类型:

interface Ixx 
{
    X: string;
}

interface Ixy extends Ixx
{
    Y: string;
}
interface Ixz extends Ixx
{
    Z: string;
}

export function update(json: Ixx) {
    var a = json.X;
}

export function update1(json: Ixy) {
   update(json);
}
export function update2(json: Ixz) {
   update(json);
}

这是有效的,因为Ixyand Ixzboth extendIxx等都满足条件json is Ixx。这也适用于扩展基类的类(或扩展基接口的类)。

目前关于 TypeScript 的文献还不多,所以也许对其他语言的接口进行一些一般性的介绍会很有用,因为这实际上是一个关于接口使用的跨语言问题,而不是任何特定于 TS 的问题。

Java 接口:http ://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html

C# 接口: http: //www.codeproject.com/Articles/18743/Interfaces-in-C-For-Beginners

于 2012-11-14T09:55:02.077 回答