Home > Enterprise >  Rest parameters typing
Rest parameters typing

Time:11-29

I have something like this:

interface Options {
  // ...
  f: (a: number, ...rest: any[]) => number[];
}

And hundreds of files using that interface, some files use it like this (contrived examples):

const options: Options = {
    // ...
    f(a, b) {
        console.log(b);
        return [a];
    }
}

And some other files use it like this:

const options: Options = {
    // ...
    f(a) {
        return [a];
    }
}

I want to modify the interface to type check the rest params without having to modify all the files using it.

I did some tests and I know that I can type the rest params of a function in the following way:

// Works like a charm!
function f<T extends unknown[]>(n: number, ...rest: T) {
    return [n, ...rest];
}

const a = f(1)
const b = f(1, {"c": "d"});

But when trying to implement it on the interface like this:

interface Options {
  // ...
  f: <T extends unknown[]>(a: number, ...rest: T) => number[];
}

I get a TS error:

const opt1: Options = {
    // TS Error!
    f(a, b) {
        console.log(b);
        return [a];
    }
}

const opt2: Options = {
    // TS Error!
    f(a) {
        return [a];
    }
}

Here is a playground with the above example and the errors, which I haven't figure out how to solve.

Any ideas on how to achieve this?

CodePudding user response:

This variation on your interface should resolve the compiler errors, and allow you to leave your other code as-is:

interface Opt<T extends unknown[] = unknown[]> {
  f: (a: number, ...rest: T) => number[];
}

Your playground code, updated

  • Related