I'm converting some JavaScript to Typescript.
In the following code, null is rejected on the basis that it cannot be assigned to a string parameter.
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttributeNS(null, 'width', canvas.width.toString());
svg.setAttributeNS(null, 'height', canvas.height.toString());
Inspecting the type of svg, we find that it is SVGSVGElement (yes, SVG occurs twice in the name). I tried explicitly specifying a type svg: SVGElement and was able to assign the created element to it, but there was no effect on the null problem.
The accepted answer to Difference between setAttribute and setAttributeNS(null, says I must pass null when the attribute has no defined namespace. It then advises me to use setAttributeNS "for consistency".
But I can't pass null. Should I pass an empty string? Would that work? or should I use the DOM level 1 setAttribute method?
If the documentation says null is allowed then this seems like an oversight in the definition unfortunately.
Fortunately you can easily work around it. Typescript supports interface declaration merging so you can redeclare the Element interface in your file and add the missing method:
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
interface Element {
setAttributeNS(namespaceURI: null, qualifiedName: string, value: string): void;
}
declare var canvas : HTMLCanvasElement;
svg.setAttributeNS(null, 'width', canvas.width.toString());
svg.setAttributeNS(null, 'height', canvas.height.toString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With