typed-html icon indicating copy to clipboard operation
typed-html copied to clipboard

required bug / string|undefined -> boolean

Open mrinc opened this issue 1 year ago • 0 comments

Ref: https://github.com/nicojs/typed-html/blob/88a6a6219bbf4d9368537ee29419d29671573093/src/jsx/element-types.d.ts#L150

As this is a string|undefined, it denotes required or not defined as per html spec... but...
If you pass in undefined the following error occurs:

https://github.com/nicojs/typed-html/blob/88a6a6219bbf4d9368537ee29419d29671573093/src/elements.tsx#L66

TypeError: Cannot read properties of undefined (reading 'toString')

2 step recommendation:

https://github.com/nicojs/typed-html/blob/88a6a6219bbf4d9368537ee29419d29671573093/src/jsx/element-types.d.ts#L150
From: required?: string;
To: required?: boolean;

  • AND

https://github.com/nicojs/typed-html/blob/88a6a6219bbf4d9368537ee29419d29671573093/src/elements.tsx#L66
From:

return makeAttribute(escapeAttrNodeValue(value.toString()));

To:

return makeAttribute(value !== undefined && value !== null && typeof value.toString === 'function' ? escapeAttrNodeValue(value.toString()) : '');
  • OR
const attributeToString = (attributes: Attributes) => (name: string): string => {
    const value = attributes[name];
    const formattedName = toKebabCase(name);
    const makeAttribute = (value: string) => `${formattedName}="${value}"`;
    if (typeof value === 'undefined') {
        return '';
    }
    if (value instanceof Date) {
        return makeAttribute(value.toISOString());
    } else switch (typeof value) {
        case 'boolean':
            // https://www.w3.org/TR/2008/WD-html5-20080610/semantics.html#boolean
            if (value) {
                return formattedName;
            } else {
                return '';
            }
        default:
            return makeAttribute(escapeAttrNodeValue(value.toString()));
    }
};

Happy to push a PR for this, let me know.

mrinc avatar Jan 16 '24 08:01 mrinc