Typed OM
Learn type-safe values with CSS Typed OM.
What is the Typed OM?
The CSS Typed OM gives values as objects instead of strings. element.computedStyleMap().get('width') returns a CSSUnitValue; .value gives the number, .unit the unit.
This removes the cost of parsing strings and gives type safety. You no longer split the '16px' string by hand; the browser hands you a ready object. This also lowers the risk of mistakes in animation math.
CSSUnitValue and CSSNumericValue
CSSUnitValue is the most common value type: something like { value: 16, unit: 'px' }. CSSNumericValue is the base class; with add, sub, mul you do type-safe math.
For example width.add(CSS.px(10)) returns a new value object; no string parsing. This matters in calculation-heavy animations.
Exercise Write a transition on a typed variable
Complete the CSS below. In .pulse add transition: --pulse-color 0.4s ease and background: var(--pulse-color). (--pulse-color was registered as typed with @property earlier.)
Show example solution
/* transition on a typed variable */
.pulse {
transition: --pulse-color 0.4s ease;
background: var(--pulse-color);
}
Test yourself
-
What does the .unit field of a CSSUnitValue give?
const v = el.computedStyleMap().get('width'); /* what does .unit give? */- A raw number
- The unit of the value (px, %, etc.)
- The selector name
- The worklet name
Show answer
The unit of the value (px, %, etc.) — Correct. .unit gives the unit string such as 'px' or '%'.
-
Get the number from the computed width
const w = el.computedStyleMap().get('width'); const px = w.____;Show answer
const w = el.computedStyleMap().get('width'); const px = w.value; -
Match the Typed OM concepts
- computedStyleMap
- Gives computed values
- CSSUnitValue
- Number + unit object
- .value
- Numeric part
- .unit
- Unit string