Here's a high-level overview of concepts in TypeScript, along with code snippets to illustrate each one. Remember, this is a brief introduction and not exhaustive. You might need to refer to official TypeScript documentation or books for detailed study.
- Installation and Compilation
Before you start, you need to install Node.js and npm. Then, install TypeScript globally using npm.
npm install -g typescript
To compile a TypeScript file (.ts) to JavaScript (.js), use the tsc
command.
tsc yourfile.ts
- Basic Types
TypeScript supports basic data types like string
, number
, boolean
, array
, any
, void
, null
, and undefined
.
let isDone: boolean = false;
let decimal: number = 6;
let color: string = "blue";
let list: number[] = [1, 2, 3];
let notSure: any = 4;
- Enum
An enumeration is a way of giving friendly names to sets of numeric values.
enum Color {Red = 1, Green, Blue}
let c: Color = Color.Green;
- Tuple
Tuple types allow you to express an array with a fixed number of elements whose types are known, but need not be the same.
let x: [string, number];
x = ["hello", 10];
- Interface
Interfaces in TypeScript are used to tell the compiler what the shape of the JS object should look like. It is a way to ensure that a class meets a certain contract.
interface LabelledValue {
label: string;
}
function printLabel(labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
- Class
Like JavaScript, TypeScript also has classes to work with object-oriented programming.
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
- Generics
Generics provide a way to make components work with any data type and not restrict to one data type. They make the component reusable.
function identity<T>(arg: T): T {
return arg;
}
- Modules
TypeScript has internal and external modules to handle large applications.
import * as math from "lib/math";
console.log("2Ï€ = " + math.sum(math.pi, math.pi));
- Decorators
Decorators provide a way to add both annotations and a meta-programming syntax for class declarations and members.
@sealed
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
- Advanced Types
Advanced types in TypeScript include union types, type guards, type aliases, string literal types, numeric literal types, and more.
type StringOrNumber = string | number;
function padLeft(value: string, padding: StringOrNumber) {
// ...
}
React with TypeScript
Create React App (CRA) provides a convenient way to start building a new React single page application, and it has built-in support for TypeScript.
- Create a new React project with TypeScript:
npx create-react-app my-app --template typescript
This will set up a new React application named "my-app" with TypeScript support enabled. The files will have the .tsx
extension, and you can use TypeScript throughout the application.
- Once you have the TypeScript React app set up, you can create React components like this:
// App.tsx
import React from 'react';
interface AppProps {
message: string;
}
const App: React.FC<AppProps> = ({ message }) => {
return (
<div>{message}</div>
);
};
export default App;
Here, React.FC<AppProps>
is a type that says "this is a React functional component, and it expects to receive props of type AppProps
."
Node.js with TypeScript
- First, create a new Node.js project and navigate into the project directory:
mkdir my-node-app
cd my-node-app
- Then, initialize a new Node.js project:
npm init -y
- After that, install TypeScript and ts-node, a tool that we will use to execute TypeScript directly:
npm install typescript ts-node --save-dev
- Initialize a new TypeScript configuration file:
npx tsc --init
- Edit the generated
tsconfig.json
file according to your needs. You might want to change the "target" property to a more recent version of ECMAScript, and the "rootDir" property to "src", if you plan on organizing your code in a "src" directory:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"rootDir": "src",
"outDir": "dist",
"strict": true,
"esModuleInterop": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}
- Create an example TypeScript file
src/index.ts
:
const message: string = 'Hello, Node.js with TypeScript!';
console.log(message);
- Now, add a start script in your
package.json
:
"scripts": {
"start": "ts-node src/index.ts"
}
- Finally, start the Node.js application:
npm start
These steps will help you set up a new React or Node.js application with TypeScript. For an existing application, the process would be similar, but you'd have to convert existing JavaScript files to TypeScript and fix any type errors that TypeScript finds.
Remember, TypeScript is a superset of JavaScript, so all JavaScript features and concepts also apply to TypeScript.