可以在Typescript中扩展类型吗?

编程入门 行业动态 更新时间:2024-10-28 02:33:55
本文介绍了可以在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 ,现在可以有一个扩展类似对象类型的界面:

type Event = { name: string; dateCreated: string; type: string; } interface UserEvent extends Event { UserId: string; }

它不起作用 - UserEvent如果要使用 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.

更多推荐

可以在Typescript中扩展类型吗?

本文发布于:2023-07-16 22:55:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1126797.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   Typescript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!