Ошибка TS2339: Property 'styleSheet' does not exist on type 'HTMLStyleElement'

Рейтинг: 0Ответов: 1Опубликовано: 29.03.2023
    var css = '@page { size: landscape; }',
        head = document.head || document.getElementsByTagName('head')[0],
        style = document.createElement('style');

    style.type = 'text/css';
    style.media = 'print';

    if (style.styleSheet) {
        style.styleSheet.cssText = css;
    } else {
        style.appendChild(document.createTextNode(css));
    }

    head.appendChild(style);
Ругается на styleSheet

Ответы

▲ 1Принят

Встроенный тип HTMLStyleElement вашей версии TypeScript не содержит информации об особенностях IE8 и ниже.

Вы можете создать свой уточненный тип, доопределить недостающие свойства и указать тип явно:

type IE8HTMLStyleElement = HTMLStyleElement & {styleSheet?: {cssText: string}};   
var style: IE8HTMLStyleElement = document.createElement('style');