如何在TypeScript中使用自定义属性指定数组类型?

时间:2019-06-05 20:14:10

标签: typescript

例如,如果我将附加数据(以键-值对的形式,其中键是字符串)附加到数组实例,那么我如何扩展该数组实例的类型以允许该附加实例数据?

const associativeArray: string[] & Record<string, string> = ['some', 'array', 'data']
/*
Type 'never[]' is not assignable to type 'string[] & Record<string, string>'.
  Type 'never[]' is not assignable to type 'Record<string, string>'.
    Index signature is missing in type 'never[]'.ts(2322)
*/

associativeArray.customKey = 'customValue'

1 个答案:

答案 0 :(得分:1)

自打字稿1.6起,您可以extend array types

class MyArray extends Array<string> {
  customKey?: string;
}

但是,使用任意字符串键这样做可能不是一个好主意,因为使用数字字符串仍然会影响length之类的数组行为,并且因为您可以覆盖Javascript和Typescript中的Array属性和方法。如果允许使用任意字符串键,则可能会失去键入对象的许多好处。

foo = ["a", "b", "c"];
console.log(foo.length);                        // 3
foo.arbitraryString = "arbitrary";
console.log(foo.length);                        // 3
foo["anotherArbitraryString"] = "arbitrary";
console.log(foo.length);                        // 3
foo["3"] = "d";
console.log(foo.length);                        // 4
foo["push"] = () => console.log("Oops.");
foo.push("e");                                  // Oops.

[Fiddle]

在任何情况下,equivalent and more idiomatic都比[key: string]: string使用Record<string, string>作为属性。