Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

javascript - Is there any downside to using .tsx instead of .ts all the times in typescript?

I just start working on a React project with TypeScript and ask myself what should I do with regular class files? Should I use .ts or .tsx files and then I couldn't find any reason to do not using .tsx file all the times even when it's not a React project!

Is there any reason or specific situation that we shouldn't use .tsx files? if no, why TypeScript team add whole new extension?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use tsx instead of ts with very little difference. tsx obviously allows the usage of jsx tags inside TypeScript, but this introduces some parsing ambiguities that make tsx slightly different. In my experience these differences are not very big:

Type assertions with <> don't work as that is the marker for a jsx tag.

TypeScript has two syntaxes for type assertions. They both do the exact same thing but one is usable in tsx the other is not:

let a: any;
let s = a as string // ok in tsx and ts
let s2 = <string>a // only valid in ts

I would use as instead of <> in ts files as well for consistency. as was actually introduced in TypeScript because <> was not usable in tsx.

Generic arrow functions with no constraint are not parsed correctly

The arrow function below is ok in ts but an error in tsx as <T> is interpreted as the start of a tag in tsx:

 const fn = <T>(a: T) => a

You can get around this either by adding a constraint or not using an arrow function:

 const fn = <T extends any>(a: T) => a
 const fn = <T,>(a: T) => a // this also works but looks weird IMO
 const fn = function<T>(a: T) { return a;}

Note

While you can use tsx instead of ts, I would recommend against it. Convention is a powerful thing, people associate tsx with jsx and will probably be surprised you don't have any jsx tags, best keep developer surprise to a minimum.

While the ambiguities above (although probably not a complete list) are not big they probably played a big part in the decision to use a dedicated file extension for the new syntax in order to keep ts files backward compatible.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...