Skip to content

Commit

Permalink
fix: validation of rest parameters (#7433)
Browse files Browse the repository at this point in the history
  • Loading branch information
AlCalzone authored Nov 22, 2024
1 parent d0c6340 commit 44e40da
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 3 deletions.
12 changes: 9 additions & 3 deletions packages/transformers/src/validateArgs/transformProgram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,11 +148,12 @@ export default function transformProgram(
const methodName = method?.getName();
if (!methodName) return;

const parameters = method
const parameters: ParameterInfo[] = method
.getParameters()
.map((p) => {
return {
name: p.getName(),
isRest: p.isRestParameter(),
type: p.getType(),
typeName: p.getTypeNode()?.getText(),
};
Expand Down Expand Up @@ -188,9 +189,13 @@ export default function transformProgram(
of withMethodAndClassName
) {
const paramSpreadWithUnknown = parameters.map((p) =>
`${p.name}: unknown`
`${p.isRest ? "..." : ""}${p.name}: unknown${
p.isRest ? "[]" : ""
}`
).join(", ");
const paramSpread = parameters.map((p) =>
`${p.isRest ? "..." : ""}${p.name}`
).join(", ");
const paramSpread = parameters.map((p) => p.name).join(", ");

const context: TransformContext = {
sourceFile: mfile,
Expand Down Expand Up @@ -267,6 +272,7 @@ function getTypeName(t: Type<tsm.Type>): string {

interface ParameterInfo {
name: string;
isRest?: boolean;
type: Type<tsm.Type>;
typeName: string | undefined;
}
Expand Down
58 changes: 58 additions & 0 deletions packages/transformers/test/fixtures/testSpread.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/* eslint-disable @typescript-eslint/no-unused-expressions */
import { validateArgs } from "@zwave-js/transformers";
import assert from "node:assert";

class Test {
@validateArgs()
foo(...args: number[]): void {
args;
return void 0;
}

@validateArgs()
bar(arg1: string, ...rest: boolean[]): void {
arg1;
rest;
return void 0;
}
}

const test = new Test();
// These should not throw
test.foo();
test.foo(1);
test.foo(2, 2);

test.bar("a");
test.bar("a", true);
test.bar("a", true, false);
test.bar("a", true, false, true);

// These should throw
assert.throws(
// @ts-expect-error
() => test.foo(true, 1),
/args is not assignable to Array<number>/,
);
assert.throws(
// @ts-expect-error
() => test.foo(true, 1),
/args\[0\] to be a number, got true/,
);

assert.throws(
// @ts-expect-error
() => test.foo(undefined),
/args\[0\] to be a number, got undefined/,
);

assert.throws(
// @ts-expect-error
() => test.bar("a", 1),
/rest is not assignable to Array<boolean>/,
);
assert.throws(
// @ts-expect-error
() => test.bar("a", 1),
/rest\[0\] to be a boolean, got 1/,
);

0 comments on commit 44e40da

Please sign in to comment.