3

Is there a way in TypeScript to define a type or an interface for an array to accept random string properties? For example, in JavaScript we can do the following:

const list = [ 1, 2, 3, 4, 5 ];
list.foo = 'bar';
console.log(a); // [ 1, 2, 3, 4, 5, foo: 'bar' ]
console.log(a[1]); // 2
console.log(a.foo); // 'bar'

I would like to define an interface or a type in TypeScript that allows such an array. I have tried the following:

interface IList extends Array<number> {
    [key: string]: string;
}

But it generates a series of errors that existing array methods are not assignable to type string.

I can have specific keys set in that interface (e.g., foo: string;, but I was wondering if there is a way to allow random string properties?

1
  • Do you have a real use-case for using a non-numeric index in an Array? That's super weird and kind of exactly what Objects are made for. Also note that in your above example, list.length === 5 despite the additional foo, and iterators (like map) won't encounter it. Commented Mar 22, 2018 at 19:49

1 Answer 1

3

You can define the type by using the type keyword and an intersection:

type IList = number[] & {
    [key: string]: string;
}

But assigning a value to that type is a little tricky, since an array isn't assignable to it (since arrays lack the string index signature). To fix that, you'll have to manually cast your array to that type when you assign it:

const x: IList = [1, 2, 3]; // Error: Index signature missing in type number[]
const y = [1, 2, 3] as IList; // Okay

Then:

y[0] // inferred as number
y["foo"] // inferred as string
y.filter(x => x % 2); // inferred as number[]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.