TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

TSX variable element

Open RylanH opened this issue 10 years ago • 4 comments

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';
}

RylanH avatar May 10 '16 20:05 RylanH

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:

basarat avatar May 11 '16 02:05 basarat

@sandersn could i take this bug ?

yuit avatar Jun 14 '16 14:06 yuit

Sure, I haven't looked at it at all.

sandersn avatar Jun 14 '16 14:06 sandersn

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

yuit avatar Jun 23 '16 21:06 yuit