microsoft / microsoft/TypeScript

Can not specify toString/valueOf methods in object literal

Open
#18,537 3 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: check: Excess Property Checking Needs Human Review
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 2.5.2

Code

interface X {
	name: string
}

const x1: X = {
	get name() { return 'x1' },
	toString() { return this.name },
//	^^^^^^^^
//	Type '{ readonly name: string; toString(): string; }' is not assignable to type 'X'.
//	Object literal may only specify known properties, and 'toString' does not exist in type 'X'.
}
const x2: X = {name: 'x2'}
x2.toString = function () { return this.name } // But add `toString` later is allowed.

Expected behavior:

Should allow object literal specify toString, valueOf and all properties exists on Object.prototype, or at least improve the error report to give a workaround (const x: X & Object).

Actual behavior:

See comments in code.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the TypeScript 2.5.2 reproduction in the issue and compare object-literal excess-property checking for toString/valueOf with assigning the same method after initialization. Determine whether Object.prototype members should be accepted or whether the diagnostic should suggest the shown X & Object workaround. Done means the chosen behavior is implemented and covered by a regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.