Today you will learn the fundamentals of TypeScript Core Types.
What is Typescript?
TypeScript is a superset of JavaScript, which means that it builds upon JavaScript and adds more features to it. One of the key features of TypeScript is the ability to define types, which helps in catching errors early on in the development process.
The Core Types in TypeScript include:
Boolean - represents a logical value of true or false.
Number - represents a numeric value.
String - represents a textual value.
Array - represents a collection of elements of the same type.
Tuple - represents an array with a fixed number of elements.
Enum - represents a set of named constants.
Any - represents any type.
Void - represents the absence of a value.
Null - represents a null value.
Undefined - represents an undefined value.
Never - represents a value that will never occur.
Here are some examples of how to use Core Types in TypeScript:
Core Types of TypeScript
Boolean
Represents a logical value of either true or false.
let isDone: boolean = false;
Number
Represents both integer and floating-point numbers.
let decimal: number = 6;
let hex: number = 5.0
String
Represents textual data. Can be enclosed in either single quotes or double quotes.
let color: string = "blue";
let sentence: string = `The color is ${color}.`;
Enum
Represents a set of named constants.
enum Color {
Red,
Green,
Blue
}
let c: Color = Color.Green;
Any
Represents a value of any type.
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false;
Void
Represents the absence of a value.
function logMessage(): void {
console.log("This is a log message.");
}
Null and Undefined
Represent the absence of a value, but are distinct types.
let u: undefined = undefined;
let n: null = null;
Never
Represents a value that never occurs.
function error(message: string): never {
throw new Error(message);
}
Object
Represents a non-primitive type.
function create(o: object | null): void;
create({ prop: 0 });
create(null);
In Typescript, it is possible to have nested types, where a type is defined within another type. Here is an example of a nested type:
type User = {
name: string;
age: number;
address: {
street: string;
city: string;
state: string;
zip: number;
};
};
In this example, the User
type has a property called address
, which is an object that has its own properties for street
, city
, state
, and zip
. To access these nested properties, you would use dot notation like so:
const user: User = {
name: "Bipin",
age: 20,
address: {
street: "123 Main St",
city: "Mumbai",
state: "Maharshtra",
zip: 12345,
},
};
console.log(user.address.street); // Output: "123 Main St"
This allows for more complex data structures to be defined with TypeScript's strong typing system.
Array
Arrays are represented by two different syntaxes in TypeScript:
Type[] syntax
The first syntax uses the square brackets and type name after the variable name:
let list: number[] = [1, 2, 3];
Array<type> syntax
The second syntax is similar to the first, but uses the Array<type> generic type:
let list: Array<number> = [1, 2, 3];
Tuple
A tuple is an array with a fixed number of elements of different types. The types of the elements are known, and they do not have to be the same. The following is an example of a tuple:
let tuple: [string, number] = ["hello", 10];
In this example, tuple
is an array of two elements. The first element is a string, and the second element is a number.
Understanding Core Types is essential for writing efficient and error-free TypeScript code. This blog provides a detailed explanation of each Core Type and how to use them in TypeScript projects. By the end of this blog, you will have a thorough understanding of TypeScript Core Types and be able to use them to write better code.
Here's an example of the React project for a to-do list using TypeScript, which includes CRUD operations:
import React, { useState } from "react";
interface Todo {
id: number;
text: string;
completed: boolean;
}
const initialTodos: Todo[] = [
{ id: 1, text: "Start learning TypeScript", completed: false },
{ id: 2, text: "Practice React", completed: true },
];
const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>(initialTodos);
const [newTodo, setNewTodo] = useState<string>("");
const handleAddTodo = () => {
const newId = todos.length + 1;
const newTodoItem: Todo = { id: newId, text: newTodo, completed: false };
setTodos([...todos, newTodoItem]);
setNewTodo("");
};
const handleToggleCompleted = (id: number) => {
const updatedTodos = todos.map((todo) => {
if (todo.id === id) {
return { ...todo, completed: !todo.completed };
} else {
return todo;
}
});
setTodos(updatedTodos);
};
const handleDeleteTodo = (id: number) => {
const updatedTodos = todos.filter((todo) => todo.id !== id);
setTodos(updatedTodos);
};
const handleEditTodo = (id: number, newText: string) => {
const updatedTodos = todos.map((todo) => {
if (todo.id === id) {
return { ...todo, text: newText };
} else {
return todo;
}
});
setTodos(updatedTodos);
};
return (
<div>
<h1>To-Do List</h1>
<ul>
{todos.map((todo) => (
<li key={todo.id}>
<label>
<input
type="checkbox"
checked={todo.completed}
onChange={() => handleToggleCompleted(todo.id)}
/>
{todo.text}
</label>
<button onClick={() => handleDeleteTodo(todo.id)}>Delete</button>
<button onClick={() => handleEditTodo(todo.id, todo.text)}>Edit</button>
</li>
))}
</ul>
<div>
<input
type="text"
value={newTodo}
onChange={(e) => setNewTodo(e.target.value)}
/>
<button onClick={handleAddTodo}>Add Todo</button>
</div>
</div>
);
};
export default App;
This code adds CRUD (Create, Read, Update, Delete) operations to the previous project. The handleAddTodo
function adds a new todo to the list, the handleToggleCompleted
function toggles the completed status of a todo, the handleDeleteTodo
function deletes a todo from the list, and the handleEditTodo
function updates the text of a todo. The return
statement renders a list of todos with buttons to delete or edit each todo, and a form to add a new todo.
This example demonstrates how TypeScript can be used in a React project to define interfaces and catch errors early on in the development process, while also providing basic CRUD functionality for a to-do list app.
Do check out these links where I have shown how to use typescript in react App :
https://codesandbox.io/s/typescript-practise-o9l5w4
https://codesandbox.io/s/typescript-with-react-js-zlny17?file=/src/App.tsx
Feel free to give suggestions.