扩展类和接口的打字稿泛型 [英] Typescript generics extending class and interface

查看:32
本文介绍了扩展类和接口的打字稿泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Typescript 类,其中包含一个需要扩展另一个类并实现接口的泛型.这是一个例子

I have a Typescript class which includes a generic which needs to extend another class and implement an interface. Here is an example

interface IHasImage {
  imageUrl():string; 
}
class Model {
}
class View<T extends Model & IHasImage> {
}

这是我在别处见过的那种语法,但有没有办法在 Typescript 中做到这一点?

This is the sort of syntax I have seen elsewhere but is there a way of doing this in Typescript?

尝试将以下内容粘贴到 Playground:http://www.typescriptlang.org/Playground

edit: Try pasting the following in to the playground:http://www.typescriptlang.org/Playground

...[removed edit 1 code]

编辑 2:答案和推理

(我很抱歉,第一个例子有一些缺陷!)我在下面标记了正确答案,尽管它可能需要一些在此 github 问题中概述的指针 (https://github.com/Microsoft/TypeScript/issues/1885)

(I apologise, the first example had a few flaws!) I have marked the correct answer below, although it probably needs a few pointers as outlined in this github issue (https://github.com/Microsoft/TypeScript/issues/1885)

给定以下代码,您可以看到该方法有效.

Given the following code you can see the methodology works.

唯一要说的是,尝试从不扩展基类的类实现接口也会失败.但是因为 Typescript 检查是基于对象的结构,如果您手动将 name 属性添加到类中,它会成功.

The only other thing to say is that trying to implement the interface from a class that does not extend the base class also fails. However because Typescript checking is based on the structure of the object, it will succeed if you manually add the name property to the class.

这也是为什么 ModelCorrect 成功了,extends 但没有 implements.

This is also why it succeeds with the ModelCorrect which extends but doesn't implements.

推荐答案

看来这是我能找到的唯一方法.不完全干净,但它做正确的事情.

It looks like this is the only way of doing it that I can find. Not perfectly clean but it does the right thing.

interface IHasImage extends Model{  
  imageUrl():string; 
}

class Model {
}

class View<T extends IHasImage> {
}

这是操场上验证它有效的屏幕截图:

Here is a screenshot from the playground verifying that it works:

​​

添加了正确的解决方法.

Added correct workaround.

这篇关于扩展类和接口的打字稿泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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