且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在打字稿中始终使用.tsx而不是.ts有什么弊端吗?

更新时间:2022-12-24 07:44:52

您可以使用 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.