Typescript: Improve CSSStyleDeclaration typings

Created on 16 Aug 2017  路  6Comments  路  Source: microsoft/TypeScript

Not every string should be allowed in properties of the CSSStyleDeclaration interface, such as display, overflow, etc. The TypeStyle project seems to have put quite some effort into this already, from which _inspiration_ could be taken.

lib.d.ts In Discussion Suggestion

Most helpful comment

Just a question: Why is the index type of CSSStyleDeclaration's index signature number and not string?

In case you want to apply a list of styles to HTMLElement.style one (like me) could try:

let element: HTMLElement = window.document.create('div');
let styles: { [key: string]: string } = {
    display: 'inline-block',
    width: '36px',
    height: '36px'
};

for (let style in styles) {
    element.style[style] = styles[style]; // generates TS7015, because index type is not 'number'
}

My current workaround is a cast to any:

(<any>element.style)[style] = styles[style];

which is really ugly.

All 6 comments

I've just been told about https://github.com/frenic/csstype and wanted to share it with you as well since it could be of help in resolving this issue.

Just a question: Why is the index type of CSSStyleDeclaration's index signature number and not string?

In case you want to apply a list of styles to HTMLElement.style one (like me) could try:

let element: HTMLElement = window.document.create('div');
let styles: { [key: string]: string } = {
    display: 'inline-block',
    width: '36px',
    height: '36px'
};

for (let style in styles) {
    element.style[style] = styles[style]; // generates TS7015, because index type is not 'number'
}

My current workaround is a cast to any:

(<any>element.style)[style] = styles[style];

which is really ugly.

It appears that somebody contributed a potential fix:
https://github.com/microsoft/TypeScript/pull/35107

The bot declined it:

It looks like you've sent a pull request to update some generated declaration files related to the DOM. These files aren't meant to be edited by hand, as they are synchronized with files in the TSJS-lib-generator repository. You can read more here. For house-keeping purposes, this pull request will be closed.

And after a quick look into the TSJS-lib-generator repo... it looks like no changes related to this have happened there yet:

https://github.com/microsoft/TSJS-lib-generator/blob/master/baselines/dom.generated.d.ts#L3196

I would like to add to the opinion that this is a real issue that needs to be addressed.

Is there any special reason this line is has index: number and not a index: string?

https://github.com/microsoft/TSJS-lib-generator/blob/bf671e99615b06404db7a89fa9ae05bf14a8e47c/baselines/dom.generated.d.ts#L3201

Wow, today I learned! Thank you.

Was this page helpful?
0 / 5 - 0 ratings