0

Is it possible to create an interface that reflects the type generated by:

const foo = Object.assign([1,2,3], {offset: 4});

I was considering:

interface Bar {
    [key: number]: number;
    offset: number;
}

But I still get errors when accessing Array prototypes (map/reduce/etc).

1
  • 1
    number[] & { offset: number }? You can't access array methods because you've only provided an index signature, not an array's methods. You need an intersection with an array type. Commented Jul 9, 2019 at 20:39

1 Answer 1

4

It seems that you can have your interface Bar to be extending Array class:

const foo = Object.assign([1,2,3], {offset: 4});

interface Bar extends Array<Number> {
    offset: number;
}

function test(a: Bar) {
    console.log(a[0]);
    console.log(a.length);
    console.log(a.concat);
}

test(foo);

You can read more about Interfaces Extending Classes

UPDATE: In fact, you can create a separate type using intersections instead of creating a separate interface:

const foo = Object.assign([1,2,3], {offset: 4});

type Bar = number[] & {offset: number};

function test(a: Bar) {
    console.log(a[0]);
    console.log(a.length);
    console.log(a.concat);
}

test(foo);
Sign up to request clarification or add additional context in comments.

10 Comments

@Bradd you might be ok just with interface Bar extends Array<Number> { offset: number; } then
@falinsky I think OP was using the interface as this is common in many langauges and is probably unaware of intersections, suggesting a different more in tune with the language solution seems reasonable to me
@TobiasTengler run: console.log(Object.assign([1,2,3], {offset: 4})) and see the output. It does in fact work. Arrays are Objects like everything else in JavaScript.
@falinsky Nah, You answer is fine, this is mostly nit picking, I don't see a reason to provide another similar answer. This would be it: typescriptlang.org/play/#code/…
check your browser console @TobiasTengler, your result has to do with their parser.
|

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.