Typescript: Type casting seems impossible in a React TSX file

Created on 4 Feb 2016  ·  3Comments  ·  Source: microsoft/TypeScript

It appears I can't use type casting in React TSX files.

Say I have this expression in some method of the React TSX component:

var editTitle = <EditableField>this.refs['editTitle'];

This line is supposed to be: fetch the child component ref'd as "editTitle" and cast it to the type EditableField, so that I can then access methods of EditableField in a strongly-typed manner.

But the typescript compiler appears to be treat that cast expression as a React element creation expression instead, being inside a TSX file and all.

Is it even possible to cast objects inside a React TSX component?

Question

Most helpful comment

Yup, we introduced the as operator for this. It's usable in both .ts and .tsx files.

All 3 comments

Ok, it appears I can use the as operator to do this. If direct casting via <> is not possible, then feel free to close.

Yup, we introduced the as operator for this. It's usable in both .ts and .tsx files.

For completeness in case anyone stumbles across this page. This is the correct way to inline cast in TSX.

(myObject as ObjectType).myProperty = 'foo';
Was this page helpful?
0 / 5 - 0 ratings