有没有办法“提取"?TypeScript 接口属性的类型?

编程入门 行业动态 更新时间:2024-10-22 14:29:28
本文介绍了有没有办法“提取"?TypeScript 接口属性的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设有一个库 X 的类型文件,其中包含一些接口.

Let's suppose there's a typing file for library X which includes some interfaces.

interface I1 { x: any; } interface I2 { y: { a: I1, b: I1, c: I1 } z: any }

为了使用这个库,我需要传递一个与 I2.y 类型完全相同的对象.我当然可以在我的源文件中创建相同的界面:

In order to work with this library I need pass around an object that is of exactly the same type as I2.y. I can of course create identical interface in my source files:

interface MyInterface { a: I1, b: I1, c: I1 } let myVar: MyInterface;

但后来我承担了保持库中最新版本的负担,而且它可能非常大并导致大量代码重复.

but then I get the burden of keeping it up to date with the one from library, moreover it can be very large and result in lot of code duplication.

因此,有没有什么办法可以提取"?接口的这个特定属性的类型?类似于 let myVar: typeof I2.y(它不起作用并导致无法找到名称 I2"错误).

Therefore, is there any way to "extract" the type of this specific property of the interface? Something similar to let myVar: typeof I2.y (which doesn't work and results in "Cannot find name I2" error).

编辑:在 TS Playground 中玩了一会儿后,我注意到以下代码完全达到了我想要的效果:

Edit: after playing a bit in TS Playground I noticed that following code achieves exactly what I want to:

declare var x: I2; let y: typeof x.y;

然而,它需要声明一个冗余变量x.我正在寻找一种无需声明即可实现这一目标的方法.

However it requires a redundant variable x to be declared. I am looking for a way to achieve this without that declaration.

推荐答案

以前不可能,但幸运的是现在可以了,因为 TypeScript 2.1 版.它于 2016 年 12 月 7 日发布,它引入了索引访问类型,也称为查找类型.

It wasn't possible before but luckily it is now, since TypeScript version 2.1. It has been released on the 7th of December 2016 and it introduces indexed access types also called lookup types.

语法看起来和元素访问完全一样,只是用类型代替.所以在你的情况下:

The syntax looks exactly like element access but written in place of types. So in your case:

interface I1 { x: any; } interface I2 { y: { a: I1, b: I1, c: I1 } z: any } let myVar: I2['y']; // indexed access type

现在 myVar 的类型为 I2.y.

在 TypeScript Playground.

更多推荐

有没有办法“提取"?TypeScript 接口属性的类型?

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

发布评论

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

>www.elefans.com

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