TSX variable element
TypeScript Version:
1.8.10
Code
export class Text extends React.Component<TextProps, {}> {
_tagName: string = 'div';
render() {
return (
<this._tagName />
);
}
}
export class Heading1 extends Text {
_tagName:string = 'h1';
}
Expected behavior: No error
Actual behavior: Throws compilation error 'Cannot find name this'
Workaround
export class Text extends React.Component<TextProps, {}> {
_tagName: string = 'div';
render() {
const self = this;
return (
<self._tagName />
);
}
}
export class Heading1 extends Text {
_tagName:string = 'h1';
}
Another:
const t = {tag:'h1'}
const foo = <t.tag/>
Error : JSX element t.tag does not have construct or call signatures.
I guess its valid to tag if the variable resolves to a string instead of a Call/Construct.
Warning
But not if its not dotted e.g. the following :
const tag ='h1';
const foo = <tag/>
is actually creating a React.createElement("tag") and not React.createElement("h1"). To be honest this whole use a string to point to what you want feels wrongish to me.
Type
Note : The type will probably have to resolve to any at least to begin with and it is going to be a pain :rose:
@sandersn could i take this bug ?
Sure, I haven't looked at it at all.
Update on the decision we made, after talk with @RyanCavanaugh about this. We made following decision:
- For variable (including const) that has string type, it will be resolve to anyType (i.e we will not check if the string actually has valid Jsx intrinsic element type).
- For variable with string literal type, we will check whether this string literal type is actually a valid Jsx intrinsic element type.
So in both examples pointed out by @RylanH and @basarat , the type will be anyType and no error should be reported. if you would like a tighter check, you will want to give it a string literal type