简体   繁体   English

如何在TypeScript中声明变量具有数组元素的类型?

[英]How to declare that a variable has the type of an array element in TypeScript?

In TypeScript, it is possible to declare that, eg, var b has the same type as var s : 在TypeScript中,可以声明例如var bvar s具有相同的类型:

var s = "hello";
var b: typeof s;

Is there a simple way to declare that var b has the same type as the elements in an array? 有没有一种简单的方法来声明var b与数组中的元素具有相同的类型? Here, var b should still be a string: 在这里, var b应该仍然是字符串:

var c = ["hello", "world"];
var b: typeof(c[0]);

An ugly workaround (which runs even if c is null) is: 一个丑陋的解决方法(即使c为null也会运行)是:

var c = ["hello", "world"];
var a = (<T>(x: T[]): T => null)(c);
var b: typeof a;

Is there a better way? 有没有更好的办法?

Is there a better way? 有没有更好的办法?

No. There is no dedicated syntax for it. 否。没有专用的语法。 In the absence of a dedicated syntax you fundamentally need something that takes T[] and gives you T . 在没有专用语法的情况下,您从根本上需要使用T[]并给您T You in-line function is a decent example of this generic usage. 内联函数是这种通用用法的一个很好的例子。

Couldn't find anything in the language specification about this, and to me this seems like something too trivial to be implemented; 在语言规范中找不到与此相关的任何内容,在我看来,这似乎太微不足道了,无法实现。 at least at the current stage that TypeScript is in. 至少在TypeScript处于当前阶段。

However, a shorter/simpler workaround could be: 但是,更短/更简单的解决方法可能是:

var a = 0 && c[0];
var b: typeof a;

Should work even if c is null or undefined . 即使cnullundefined也应该工作。
Much less of a performance impact as well. 对性能的影响也要少得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM