在 Typescript 中扩展泛型参数 [英] Extending a generic parameter in Typescript

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

问题描述

我想创建一个实用函数,它通过向数组中的每个项目添加一个 isChecked 敲除可观察属性来创建一个清单.此函数应如下所示:

I want to create a utility function which creates a checklist by adding an isChecked knockout observable property to each item in an array. This function should look like this:

createCheckList<T>(allEntities: T[], selected: T[]) : CheckListItem<T> {
    ...
}

我返回一个 CheckListItem 因为这个接口应该扩展 T 以添加 isChecked 属性.但是,打字稿不允许我这样做:

I am returning a CheckListItem<T> because this interface should extend T to add the isChecked property. However, typescript will not allow me to do this:

interface CheckListItem<T> extends T {
    isChecked: KnockoutObservable<boolean>;
}

给我错误:

一个接口只能扩展另一个类或接口.

An interface may only extend another class or interface.

有没有办法做到这一点?

Is there any way to do this?

推荐答案

在 TypeScript 中没有办法表达这一点.

There isn't a way to express this in TypeScript.

你显然可以这样做:

interface CheckListItem<T> {
    isChecked: KnockoutObservable<boolean>;
    item: T;
}

这样做的好处是当对象碰巧有自己的 isChecked 属性时不会破坏它.

This has the advantage of not breaking the object when it happens to have its own isChecked property.

这篇关于在 Typescript 中扩展泛型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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