问题描述
我刚刚开始使用TypeScript进行React项目,并问自己应该如何处理常规类文件?我应该使用 .ts
还是 .tsx
文件,然后我也找不到任何理由不始终使用 .tsx
文件当它不是一个React项目时!
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!
是否有任何我们不应该使用 .tsx
文件的原因或特定情况?如果没有,为什么TypeScript团队要添加整个新扩展名?
Is there any reason or specific situation that we shouldn't use .tsx
files? if no, why TypeScript team add whole new extension?
推荐答案
您可以使用 tsx
代替 ts
,差别很小. tsx
显然允许在TypeScript中使用 jsx
标记,但这引入了一些解析歧义,使tsx略有不同.根据我的经验,这些差异不是很大:
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:
带有<>
的类型断言不起作用,因为这是jsx标记的标记.
Type assertions with <>
don't work as that is the marker for a jsx tag.
TypeScript具有两种用于类型断言的语法.他们俩都做完全相同的事情,但是一个可以在tsx中使用,而另一个则不可以:
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
为了一致性,我也会在 ts
文件中使用 as
而不是<>
. as
实际上是在TypeScript中引入的,因为<>
在 tsx
中不可用.
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
.
无约束的通用箭头函数无法正确解析
下面的箭头功能在 ts
中是可以的,但是在 tsx
中作为< T>
的错误被解释为标签的开头在 tsx
中:
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;}
注意
虽然您可以使用 tsx
代替 ts
,但我还是建议您不要使用它.约定是强大的功能,人们将 tsx
与 jsx
相关联,并且可能会惊讶于您没有任何 jsx
标签,最好让开发人员感到惊讶最少.
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.
尽管上面的歧义(尽管可能不是完整的清单)并不大,但它们可能在决定使用专用文件扩展名的新语法以保留 ts
文件的过程中起了很大的作用向后兼容.
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.
这篇关于在打字稿中始终使用.tsx而不是.ts有什么弊端吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!