TypeScript:类型定义的参考子类型(接口)

编程入门 行业动态 更新时间:2024-10-22 03:58:47
本文介绍了TypeScript:类型定义的参考子类型(接口)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在我的TypScript中使用以下类型:

I am using the following type in my TypScript:

interface ExerciseData { id : number; name : string; vocabulary : { from : string; to : string; }[]; }

现在我想创建一个类型相同的变量属性词汇,尝试以下操作:

Now I'd like to create a variable that is of the same type as the attribute vocabulary, trying the following:

var vocabs : ExerciseData.vocabulary[];

但这不起作用。是否有可能以某种方式引用子类型?或者我必须做这样的事情?

But that is not working. Is it possible to reference to a subtype somehow? Or would I have to do something like this?

interface ExerciseData { id : number; name : string; vocabulary : Vocabulary[]; } interface Vocabulary { from : string; to : string; } var vocabs : Vocabulary[];

非常感谢提示。

推荐答案

不完全是你想要的,但你可以使用typof关键字解决这个问题,但前提是你有一个声明为你的接口类型的var,如下所示。请注意,我认为您在上一个代码块中所做的事情要好得多:)

Not exactly what you want but you can hack around this with the typof keyword but only if you have a var that is declared as your interface type like below. Note that I think what you did in your last codeblock is a lot better :)

interface ExerciseData { id : number; name : string; vocabulary : { from : string; to : string; }[]; } var x: ExerciseData; var vocabs : typeof x.vocabulary[];

更多推荐

TypeScript:类型定义的参考子类型(接口)

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

发布评论

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

>www.elefans.com

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