What is the difference between .ts and .tsx extensions
A file extension tells the purpose or what is inside the file.
- The
.ts
extension is used for files containing TypeScript code.
For example, functions, classes, etc. - The
.tsx
extension is used for files containing TypeScript and JSX code.
For example, React component.
You can think of it as a counterpart of .js
and .jsx
extensions.
Examples #
Here is an example of a .ts
file.
import type { NextApiRequest, NextApiResponse } from 'next'
type Data = {
name: string
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
res.status(200).json({ name: 'John Doe' })
}
Here is an example of a .tsx
file. As you can see, a Document()
function returns a JSX code.
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}