Monday, May 5, 2025

Hello Typescript world

Typescript is javascript with type. Waita minute the very reason you use javascript (rather than java) is you want to be quick-and-dirty and not want to use types right? Well if you want to use React with types you will need Typescript. Its syntax is somewhat like Pascal: See https://www.geeksforgeeks.org/hello-world-in-typescript-language/ for a quick introduction. But in React you don't compile and run. It's mostly automatic. and you are likely not going to do a lot of heavy OOP either.

Search for "react typescript hello world" and you will find several ways to do that. I use npm. First you need to install node. Then create skeleton app:

npx create-react-app my-app --template typescript
Then go to the folder
cd my-app
A bunch of things has been generated for you. Go to src/App.tsx. This is where you put your components.

Here is a simple component. Call it MyComponentFC.tsx

import React from 'react';

const MyComponentFC: React.FC<{
  name: string;
  age: number}> = ({name,age}) => {

  return (
    <h1>Hello, {name}! you are {age} years old</h1>
  );
};

export default MyComponentFC;

In React instead of making things public you "export" it so it is known to outside world. Yes, people like returning not a single value these days. People don't mind mixing code with HTML in a giant return statement. You are cranky old school if you think this isn't so elegant.

See this little component (not a class, but a constant function) takes 2 parameters and you can give each a type (and you have to repeat the names in that interesting symtax). The parameters can be much more complex than strings and numbers. The idea is define your own tags and manage states (variables) within.

This simple component generates some simple html with parameters you passed in.

That index.html is what your browser hits... which in turns calls index.tsx, which calls the App component. Here is my tweaked App.tsx to call that component. FC stands for Function Component.

import './App.css';
import MyComponentFC from './MyComponentFC';

function App() {
  return (
      <MyComponentFC name="Johnny" age={20}/>
      )
}

export default App;

Launch the app with

npm start

No comments: