Difference Between TypeScript .ts and .tsx Files

TypeScript is popular among developers who want to add type safety to their JavaScript code.

When you start using TypeScript, you will see two types of files: .ts and .tsx. It is essential to understand the differences between them, particularly when using TypeScript with React.

This tutorial explains the difference between TypeScript .ts and .tsx files, provides examples, and guides you through best practices for using each.

What is TypeScript?

TypeScript is a superset of JavaScript that adds static types. This means you can catch errors during development rather than at runtime, making your code more robust and maintainable. TypeScript files typically have the .ts extension.

What is TSX?

TSX stands for TypeScript XML. It is a syntax extension that allows you to write JSX (JavaScript XML) in TypeScript files. JSX is a syntax used by React to describe the UI that should be displayed. TSX files have the .tsx extension and are essentially TypeScript files that can contain JSX.

Difference Between TypeScript .ts and .tsx Files

Feature.ts.tsx
PurposeGeneral TypeScript codeTypeScript with JSX (React components)
JSX SupportNoYes
Use CaseNon-UI logic, utility functionsReact components, UI rendering
File Extension.ts.tsx

When to Use .ts vs .tsx

  • Use .ts: When writing TypeScript code that does not involve JSX. This includes utility functions, business logic, and any non-UI-related code.
  • Use .tsx: When writing React components or any code that involves JSX.

Setting Up a TypeScript Project

Before we delve into examples, let’s set up a TypeScript project. You’ll need Node.js and npm installed on your machine.

  1. Initialize a new project: mkdir my-typescript-project cd my-typescript-project npm init -y
  2. Install TypeScript: npm install typescript– save-dev
  3. Create a tsconfig.json file: { “compilerOptions”: { “target”: “es6”, “module”: “commonjs”, “strict”: true, “jsx”: “react” }, “include”: [“src”] }
  4. Create the project structure: bash mkdir src touch src/index.ts

Example of .ts File in TypeScript

Let’s create a simple utility function in a .ts file.

// src/utils.ts
export function add(a: number, b: number): number {
  return a + b;
}

In this example, we have a TypeScript file that defines a utility function, add, which takes two numbers and returns their sum. This file does not involve any JSX and is purely for logic.

ts file in TypeScript

Example of .tsx File in TypeScript

Now, let’s create a React component in a .tsx file.

// src/App.tsx
import React from 'react';

interface AppProps {
  message: string;
}

const App: React.FC<AppProps> = ({ message }) => {
  return <div>{message}</div>;
};

export default App;

In this example, we define a React component App that takes a message prop and displays it. The .tsx extension allows us to use JSX within our TypeScript file.

TypeScript .ts and .tsx Files

Integrating .ts and .tsx Files in TypeScript

To see how .ts and .tsx files can work together, let’s create an entry point that uses both.

// src/index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import { add } from './utils';
import App from './App';

const result = add(2, 3);

ReactDOM.render(
  <React.StrictMode>
    <App message={`The result is ${result}`} />
  </React.StrictMode>,
  document.getElementById('root')
);

In this example, we import the add function from our .ts file and the App component from our .tsx file. We then use the add function to calculate a result and pass it as a message prop to the App component.

Configuring Webpack for TypeScript

To bundle our TypeScript project, we can use Webpack. Here’s a basic setup:

  1. Install Webpack and necessary loaders: npm install webpack webpack-cli ts-loader– save-dev
  2. Create a webpack.config.js file: const path = require(‘path’); module.exports = { entry: ‘./src/index.tsx’, output: { filename: ‘bundle.js’, path: path.resolve(__dirname, ‘dist’) }, resolve: { extensions: [‘.ts,’ ‘.tsx’, ‘.js’] }, module: { rules: [ { test: /\.tsx?$/, use: ‘ts-loader’, exclude: /node_modules/ } ] } };
  3. Update package.json scripts: “scripts”: { “build”: “webpack” }
  4. Build the project: bash npm run build

Best Practices of Using .ts and .tsc Files

Use .ts for Logic and .tsx for UI

Keep your TypeScript files (.ts) focused on logic and business rules, while using TSX files (.tsx) for your React components. This separation helps maintain a clean and organized codebase.

Leverage TypeScript’s Type System

Make full use of TypeScript’s type system to define props, state, and other component-related types. This will help catch errors early and improve code readability.

// src/components/MyComponent.tsx
import React from 'react';

interface MyComponentProps {
  title: string;
  count: number;
}

const MyComponent: React.FC<MyComponentProps> = ({title, count }) => {
  return (
    <div>
      <h1>{title}</h1>
      <p>Count: {count}</p>
    </div>
  );
};

export default MyComponent;

Use TypeScript with Create React App

Create React App (CRA) supports TypeScript out of the box. You can create a new React project with TypeScript by running:

npx create-react-app my-app --template typescript

This command sets up a new React project with TypeScript configuration, saving you time on setup.

Testing .ts and .tsx Files

Use Jest and React Testing Library to test your TypeScript and TSX files. Install the necessary packages:

npm install --save-dev jest @types/jest ts-jest @testing-library/react @testing-library/jest-dom

Configure Jest in your package.json:

"jest": {
  "preset": "ts-jest",
  "testEnvironment": "jsdom",
  "transform": {
    "^.+\\.tsx?$": "ts-jest"
  },
  "moduleFileExtensions": ["ts", "tsx", "js", "jsx"]
}

Write a test for your component:

// src/components/MyComponent.test.tsx
import React from 'react';
import { render } from '@testing-library/react';
import MyComponent from './MyComponent';

test('renders title and count', () => {
  const { getByText } = render(<MyComponent title="Test Title" count={5} />);
  expect(getByText('Test Title')).toBeInTheDocument();
  expect(getByText('Count: 5')).toBeInTheDocument();
});

Summary Table

Feature.ts.tsx
PurposeGeneral TypeScript codeTypeScript with JSX (React components)
JSX SupportNoYes
Use CaseNon-UI logic, utility functionsReact components, UI rendering
File Extension.ts.tsx
ExampleUtility functions, business logicReact components, UI rendering
IntegrationNon-UI codeUI code

Conclusion

I hope you have got an idea about the difference between .ts and .tsx files, which is crucial for effectively utilizing TypeScript in your projects, particularly when working with React.

By following best practices and leveraging TypeScript’s powerful type system, you can write more maintainable and error-free code. Use .ts for your logic and utility functions, and .tsx for your React components to keep your codebase organized and clean.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.