可以在 Typescript 中扩展类型吗?

编程入门 行业动态 更新时间:2024-10-27 20:24:26
本文介绍了可以在 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 中扩展类型吗?

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

发布评论

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

>www.elefans.com

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