可以在 Typescript 中扩展类型吗? [英] Possible to extend types in Typescript?

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

问题描述

假设我有以下类型:

type Event = {
   name: string;
   dateCreated: string;
   type: string;
}

我现在想扩展这种类型,即

I now want to extend this type, i.e.

type UserEvent extends Event = {
   UserId: string; 
}

这不起作用.我该怎么做?

This doesn't work. How can I do this?

推荐答案

关键字 extends 只能用于接口和类.

The keyword extends can be used for interfaces and classes only.

如果您只想声明具有附加属性的类型,可以使用 交叉路口类型:

If you just want to declare a type that has additional properties, you can use intersection type:

type UserEvent = Event & {UserId: string}

UPDATE 对于 TypeScript 2.2,现在可以有一个界面扩展类对象类型,如果类型满足一些限制:

UPDATE for TypeScript 2.2, it's now possible to have an interface that extends object-like type, if the type satisfies some restrictions:

type Event = {
   name: string;
   dateCreated: string;
   type: string;
}

interface UserEvent extends Event {
   UserId: string; 
}

反过来不行 - UserEvent 必须声明为接口,而不是 type 如果你想使用 extends 语法.

It does not work the other way round - UserEvent must be declared as interface, not a type if you want to use extends syntax.

而且仍然无法使用 extend 任意类型 - 例如,如果 Event 是没有任何约束的类型参数,则它不起作用.

And it's still impossible to use extend with arbitrary types - for example, it does not work if Event is a type parameter without any constraints.

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

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