dsherret / dsherret/ts-morph

Parameter#setType on ObjectBindingPattern: InvalidOperationError: A child of the kind Identifier was expected.

Open
#1,350 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
6.2k
Forks
238
Avg merge
2m
Merged PRs (30d)
1

Description

**Describe the bug**

setType fails on parameters with ObjectBindingPattern

Version: 16.0.0

**To Reproduce**

call setType on the `{ x, ...rest }` parameter

```ts
import { Project, ts } from "ts-morph";

const source = `
function func(
ident,
{ x, ...rest },
) {}
`

const project = new Project();
const sourceFile = project.createSourceFile("test.ts", source);

const func = sourceFile.getFirstChildByKindOrThrow(ts.SyntaxKind.FunctionDeclaration)

for (const param of func.getParameters()) {
console.log(`param: ${param.getNameNode().getKindName()}: ${param.getText()}`)
param.setType("someType")
console.log("ok\n")
}
```

```
param: Identifier: ident
ok

param: ObjectBindingPattern: { x, ...rest }
/tmp/x/node_modules/@ts-morph/common/dist/ts-morph-common.js:448
throw new InvalidOperationError(typeof errorMessage === "string" ? errorMessage : errorMessage());
^

InvalidOperationError: A child of the kind Identifier was expected.
at Object.throwIfNullOrUndefined (/tmp/x/node_modules/@ts-morph/common/dist/ts-morph-common.js:448:19)
at ParameterDeclaration.getFirstChildByKindOrThrow (/tmp/x/node_modules/ts-morph/dist/ts-morph.js:3776:30)
at getInsertPosWhenNoType (/tmp/x/node_modules/ts-morph/dist/ts-morph.js:10077:41)
at ParameterDeclaration.setType (/tmp/x/node_modules/ts-morph/dist/ts-morph.js:10060:29)
at ParameterDeclaration.setType (/tmp/x/node_modules/ts-morph/dist/ts-morph.js:13824:23)
at file:///tmp/x/ts-morph-repro.js:17:9
```

**Expected behavior**

set type on both params: Identifier and ObjectBindingPattern

```diff
function func(
- ident,
+ ident: someType,
- { x, ...rest },
+ { x, ...rest }: someType,
) {}
```

**Details**

the code is part of a react2solid converter https://github.com/swordev/suid/pull/137

**Workaround**

dont set type on params with ObjectBindingPattern

```js
if (!param.getNameNode().isKind(ts.SyntaxKind.ObjectBindingPattern)) {
param.setType("someType")
}
```

Contributor guide

Open the contributing guide

Research direction

Read CONTRIBUTING.md, then run the supplied TypeScript reproduction against Parameter#setType. Trace getInsertPosWhenNoType and the ObjectBindingPattern path shown in the stack trace. Done means setType succeeds for both parameters and produces the expected `ident: someType` and `{ x, ...rest }: someType` output.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.