TypeScript 中带有对象的数组的类型定义

Type definition for array with objects in TypeScript

如何在 TypeScript 中为这样的数组定义类型:

export const AlternativeSpatialReferences: Array< ??? > = [
    {
        '25833': 25833
    },
    {
        '25832': 25832
    },
    {
        '25831': 25831
    },
    {
        'Google': 4326
    } 
];

现在我只使用 Array<{}>,但想要正确定义。

在打字稿中,您使用 any 类型,

any used for - 需要描述我们在编写应用程序时不知道的变量类型。

 Array<any>

如果你想要一些强类型而不是你应该用两个 属性

创建新的 class
public class KeyValue
{
  key:string;
  value:number;
}

 let myarray: KeyValue[] = new Array<KeyValue>();
 myarray.push({key: '25833' , value : 25833});
 myarray.push({key: 'Google' , value : 123});

并将您当前的数组值转换为强类型。

如果你想定义一个 属性 名称在编译时未知且值是数字的对象,你应该使用 "index signature" (感谢@Joe Clay):

interface MyObject {
    [propName: string]: number;
}

那你可以这样写:

export const AlternativeSpatialReferences: MyObject[] = [
    {
        '25833': 25833
    },
    {
        '25832': 25832
    },
    {
        '25831': 25831
    },
    {
        'Google': 4326
    } 
];