TypeScript中数组对象的类型定义

3
在TypeScript中,如何为类似这样的数组定义类型:
export const AlternativeSpatialReferences: Array< ??? > = [
    {
        '25833': 25833
    },
    {
        '25832': 25832
    },
    {
        '25831': 25831
    },
    {
        'Google': 4326
    } 
];

现在我只是使用 Array<{}>,但想要正确地定义它。
2个回答

8

如果你想定义一个属性名在编译时不确定且值为数字的对象,你应该使用“索引签名”(感谢@Joe Clay):

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

然后,您可以编写以下内容:
export const AlternativeSpatialReferences: MyObject[] = [
    {
        '25833': 25833
    },
    {
        '25832': 25832
    },
    {
        '25831': 25831
    },
    {
        'Google': 4326
    } 
];

3
如果阅读此答案的人想要查找更多信息,可以称这种语法为“索引签名”。 - Joe Clay
1
@JoeClay 谢谢,我不知道那个。我已经用这个信息更新了我的答案。 - klugjo

5
在TypeScript中,你会使用any类型,它用于描述在编写应用程序时我们不知道的变量类型。
 Array<any>

如果你想使用强类型,那么你应该创建一个具有两个属性的新类。

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});

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


3
为什么用“任何”呢?那些显然是对象。在我看来,Array<object> 更合适! - indexoutofbounds
我需要Array<any>,正如答案中所述,而不是@indexoutofbounds的评论,因为object导致了foo does not exist on {} - Timo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接