有没有办法“提取"?TypeScript 接口属性的类型? [英] Is there a way to "extract" the type of TypeScript interface property?

查看:35
本文介绍了有没有办法“提取"?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 接口属性的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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