0

window.getComputedStyle returns a value with type CSSStyleDeclaration, which has CSS properties keys in camelcase format.

However, tested both on Chrome, Firefox, and Safari, it returns the keys' values in both camelcase, and hyphen separated format, and I reference the keys with hyphen separated format:

const div = document.querySelector('div#test');
const computedStyles = window.getComputedStyle(div);

console.log(
  'marginTop:', computedStyles.marginTop,
  'margin-top:', computedStyles['margin-top']
);
div#test {
  width: 100px;
  height: 100px;
  background-color: aqua;
  margin-top: 50px;
}
<div id='test'></div>

It causes me a need to use a lot of ugly as unknown as ... when trying to get a value referencing a key (like the second case in the above example), so I've decided to add extra properties to CSSStyleDeclaration. I'm just not sure how to do it.

And just to make it crystal clear: the issue is that on CSSStyleDeclaration (the return type of window.getComputedStyle) margin-top as property doesn't exist, but the return value actually has it.

What would worth mentioning is I wouldn't like to create new, custom types. Basically I would just like to extend an already existing type, so CSSStyleDeclaration locally would have the keys already existed on it, plus my own (margin-top based on the example).

Gergő Horváth
  • 3,195
  • 4
  • 28
  • 64
  • Where would you need to use `as unknown as` when you think it could be done otherwise? Iam not sure about your problem, based on the code you provided. –  May 26 '20 at 11:38
  • Does this answer your question? [How do you explicitly set a new property on \`window\` in TypeScript?](https://stackoverflow.com/questions/12709074/how-do-you-explicitly-set-a-new-property-on-window-in-typescript) – matek997 May 26 '20 at 12:23

1 Answers1

0

The solution is to simply redeclare the type in a .d.ts file. It keeps the original properties, and add the new ones as well. Based on the example it looks like this:

declare interface CSSStyleDeclaration {
  'margin-top': string;
}
Gergő Horváth
  • 3,195
  • 4
  • 28
  • 64