Typescript: setAttribute signature too strict

Created on 25 Apr 2017  路  9Comments  路  Source: microsoft/TypeScript



TypeScript Version: 2.2.2

elm.setAttribute('disabled', true) // should be allowed
elm.setAttribute('disabled', 1) // should be allowed

Expected behavior:

value
A DOMString containing the value to assign to the attribute. Any non-string value specified is converted automatically into a string.

https://developer.mozilla.org/en/docs/Web/API/Element/setAttribute

Actual behavior:

setAttribute(name: string, value: string): void

Working as Intended

Most helpful comment

Being able to pass in a boolean or number makes sense for a lot of different types of attributes -- I support this change. It's annoying to have to do .setAttribute('aria-hidden', (!this.isVisible()).toString()) when the underlying API intentionally supports the simpler .setAttribute('aria-hidden', !this.isVisible())

I think this is different than Math.sign, since Math.sign('hello') is plainly a bug, while .setAttribute with a number or boolean is very often valid/desirable.

All 9 comments

TypeScript generally warns on implicit conversions, e.g. calling Math.sign("hello world") is an error even though the spec says "hello world" will be converted to a number automatically.

@RyanCavanaugh I think you might mean "converted to a number automatically". But I'm too laze to check what Math.sign does.

Right (fixed)

For Math.sign string might not make sense. As in the example you provided @RyanCavanaugh.

For setAttribute, I think that string | number | boolean is always reasonable, right? That's my PR:
https://github.com/Microsoft/TSJS-lib-generator/pull/237

Implicit conversion guarding is one of those great features of TypeScript. I would hate for that to be eroded.

Being able to pass in a boolean or number makes sense for a lot of different types of attributes -- I support this change. It's annoying to have to do .setAttribute('aria-hidden', (!this.isVisible()).toString()) when the underlying API intentionally supports the simpler .setAttribute('aria-hidden', !this.isVisible())

I think this is different than Math.sign, since Math.sign('hello') is plainly a bug, while .setAttribute with a number or boolean is very often valid/desirable.

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@mhegazy @RyanCavanaugh I don't agree. This needlessly limiting the DOM interface.

declare global {
  interface Element {
    setAttribute(name: string, value: boolean): void;
    setAttribute(name: string, value: number): void;
  }
}

Now you can have it without impacting everyone else.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

siddjain picture siddjain  路  3Comments

Zlatkovsky picture Zlatkovsky  路  3Comments

Roam-Cooper picture Roam-Cooper  路  3Comments

Antony-Jones picture Antony-Jones  路  3Comments

bgrieder picture bgrieder  路  3Comments