简体   繁体   English

如何确定打字稿、数字数组或字符串数​​组中的变量类型?

[英]How to determine type of variable in typescript, array of numbers or array of strings?

I have a variable like我有一个像

const data = [];

In some places in my App, data looks like string array or number array在我的应用程序的某些地方,数据看起来像字符串数组或数字数组

// data [1, 2, 3]
// data ["1", "2", "3"]

How can I get the type of this variable - type string array or number array ?我怎样才能得到这个可变类型字符串数组或数字数组的类型?

Yes you can type your variables with a single type是的,您可以使用单一类型键入变量

// type data as an array of strings
const data: string[] = [];

// type data as an array of numbers
const data: number[] = [];

// type data as an array of objects
const data: object[] = [];

If you want to use a mix of types in your array, you can type it as any .如果要在数组中混合使用类型,可以将其键入为any But this may not be a good practise.但这可能不是一个好的做法。

const data: any[] = [];

For more information about type in typescript, look here: Basic type documentation有关在打字稿中键入的更多信息,请查看此处: 基本类型文档

For defining array with multiple types, look here: https://stackoverflow.com/a/29382420/1934484要定义具有多种类型的数组,请看这里: https : //stackoverflow.com/a/29382420/1934484

@Tomas Vancoillie has the right idea. @Tomas Vancoillie 有正确的想法。

You can declare them with the : operator.您可以使用 : 运算符声明它们。

You can also infer the type with Array(), for example:您还可以使用 Array() 推断类型,例如:

let myStringArray = Array<string>();

You can define your array like this the typescript compiler will only allow strings您可以像这样定义数组,打字稿编译器只允许字符串

const array: Array<string> = [];

or if you want to have strings and numbers define it like this或者如果你想用字符串和数字来定义它

const array: Array<string | number> = [];

You can also define it this way你也可以这样定义

const array: string[] = [];
const array: (string | number)[] = [];

如果你只需要获取 中元素的类型,因为它们要么是string要么是number ,你可以只获取第一个元素的类型,因为所有其他元素都具有相同的类型:

typeof data[0] // string or number

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

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