
There are many ways typescript syntaxes are used. So here I’m going to emphasize only the most important parts of typescript which are mostly used in react/react native projects according to my experience.
In this article, I’m going to discuss mostly used TypeScript syntax from the basics to the advanced level.
Let's categorize those syntaxes,
- Variable/Constant declaration scenario (Basic data types)
- Variable/Constant declaration scenario (Advanced data types)
- Variable/Constant declaration scenario (React ecosystem-related data types)
- Custom types creation
- Custom interfaces creation
- Custom enums creation
- Prop passing scenario (Functions/Functional Component related)
- Returning scenario (Functions/Functional Component related)
- Summary of function/functional component creation
- Hooks declaration scenario (React/React Native ecosystem-related)
Variable/Constant declaration scenario (Basic data types)
Here we discuss string, number, boolean, any, null, undefined and Date data types/ interfaces.
We often get into this scenario when we are doing when declaring variables and constants. Here I’m only showing syntax for basic data type declarations. Let's see how string, number, and boolean data type declarations work.
const myVariable: string = "This is string constant declaration";
const myVariable: number = 7;
const myVariable: boolean = true;
There are special data types also. any is one of them. So any keyword goes with any type.
const myVariable: any = "Here you can declare any type with any keyword";
const myVariable: any = 77;
const myVariable: any = true;
In TypeScript, null means there is no value assigned intentionally, while undefined means a value has not been assigned at all.
const myVariable: null = null;
const myVariable: undefined = undefined;
Sometimes we have to deal with data and time in our projects. That’s when the Date interface comes in handy. I know this is not a type and Date is an interface.
const myVariable: Date = new Date();
Variable/Constant declaration scenario (Advanced data types)
Here we discuss basic functions, arrays, and object declarations.
Basic functions declaration:
const myFunction: Function = ()=>{}Also, there is another way of declaring a function. (We discuss this declaration way later)
const myFunction: () => void = () => {}Basic arrays declaration:
const myArray: number[] = [1, 2, 3, 4, 5];
const myArray: string[] = ["abc", "xyz"];
const myArray: boolean[] = [true, false, false]
There is another way.
const myArray: Array<number> = [1, 2, 3, 4, 5];
const myArray: Array<string> = ["abc", "xyz"];
const myArray: Array<boolean> = [true, false, false]
Basic object declaration:
const myObject: object = {item1: "abc", item2: 77};Also, we can define an object like this,
const myObject: {item1: string; item2: number} = {item1: 'abc', item2: 77};Variable/Constant declaration scenario (React ecosystem-related data types)
In this section, I’m going to talk about the declarations scenario which is more specific to the React Ecosystem (React/React Native).
// In React Native
const MyReactComponentFunctionReactNative: React.FC = () => {
return <Text>I'm a text component in React Native</Text>;
};
// In React
const MyReactComponentFunctionReact: React.FC = () => {
return <div>I'm a div tag React</div>;
};
Here React.FC means this is a React Functional Component. That means this is a function that is for creating a React Component.
Custom types creation
Here I’m going to talk about what a type is in TypeScript and how to create a custom type.
Types are used when the programmer needs to define intricate types that involve unions (mixing different types), mapped types (transforming types), or conditional types (types based on conditions).
In TypeScript, the type keyword is used to create an alias for a type. It allows you to give a name to a particular type or combination of types, making it easier to reference that type throughout your codebase.
Let’s find out how to create a custom type in TypeScript and how to use that.
type MyNumber = number;
const myNumberVariable: MyNumber = 77;
Let's go for the creation of a custom type that has more properties and its usage.
type Person = {
name: string;
age: number;
};
const companyPerson1: Person = {name: "Alex", age: 27};Also, there are various operations on types including unions operator, intersections operator, and optional property types.
- Unions
In the following example, | the operator means myStatus the variable can be a number or string.
type Status = number | string;
const myStatus: Status = 5;
Also, this is valid,
Here status can be type active or type inactive.
type Status = 'active' | 'inactive';
const myStatus: Status = 'active';
By this union operator, we can do this one too.
type Mode = '2D' | '3D';
type Point = {
x: number;
y: number;
mode: Mode;
};
Also here is another advanced way of using the union operator
type Mode = '2D' | '3D';
type Point = {
x: number;
y: number;
mode: Mode | '4D';
};
const point1: Point = { x: 11, y: 17, mode: '3D' };
const point2: Point = { x: 27, y: 27, mode: '4D' };
There you can see that the mode property type Role or can set type 4D.
2. Intersection
Here & operator combines the Animal type and the Bird type.
type Animal = {
name: string;
};
type Bird = {
fly: boolean;
};
type FlyingAnimal = Animal & Bird;
const eagle: FlyingAnimal = { name: 'Eagle', fly: true };3. Optional Property
Here with the ? operator we can make the property optional in a type. So the programmer can set that property or not.
type Mode = '2D' | '3D';
type Point = {
x: number;
y: number;
z?: number; // Optional Property
mode?: Mode | '4D'; // Optional Property
};
const point1: Point = { x: 11, y: 17, z: 37, mode: '3D' };
const point2: Point = { x: 27, y: 27 };
const point3: Point = { x: 11, y: 17, mode: '3D' };
Custom interfaces creation
Here I’m going to talk about custom interface creation.
Interfaces are mostly used when a programmer needs to define the structure of objects, specifying the properties they should have and their expected types.
interface Employee {
name: string;
age: number;
}
const employee1: Employee = {name: 'John', age: 30};Also in interfaces, we can extend another interface with that. For that the extends keyword is used.
interface EmployeeWithID extends Employee {
id: string;
}Also, interfaces can used in classes too. By using the implements keyword this is how it's done.
interface Employee {
name: string;
age: number;
greet: () => string;
}
class Employee implements Employee {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): string {
return "Hello, my name is " + this.name;
}
}
let employee = new Employee("John Doe", 30);Custom enums creation
Enums provide a way to define a set of named constants. To make the code readable and more maintainable programmers can create a group of related values that can be assigned symbolic names with enums.
enum Direction {
Up,
Down,
Left,
Right,
}
console.log(Direction.Up); // Output: 0
console.log(Direction.Down); // Output: 1
console.log(Direction.Left); // Output: 2
console.log(Direction.Right); // Output: 3So in enums, we cannot do operations such as union, and intersection.
Prop passing scenario (Functions/Functional Component related)
In most cases in React/React Native, we have to deal with functional components and functions. That's where this scenario comes out.
Let me give you an example. Let's say we have a function named myFunction and needed to pass a prop which is a type of number.
const myFunction: Function = (num1: number) => {};This is another way of passing that.
type CustomNumber = number;
const myFunction: Function = (num1: CustomNumber) => {};
In most cases, we have to deal with multiple props in React/React Native. Not only a single prop. This is how we can do that.
const myFunction: Function = (num1: number, num2: number) => {};This is another way of passing multiple props like that.
type NumberPack = {num1: number; num2: number};
const myFunction: Function = (props: NumberPack) => {
console.log(props.num1); // This will log value 7
console.log(props.num2); // This will log value 10
};
myFunction(7, 10);So functional components also work like the same. The only change is instead of declaring as Function type we declare that as React.FC. Let me give you an example.
type NumberPack = {num1: number; num2: number};
// In React Native
const MyReactComponentFunctionReactNative: React.FC = (props: NumberPack) => {
console.log(props.num1); // This will log value 7
console.log(props.num2); // This will log value 10
return <Text>I'm a text component in React Native</Text>;
};
// In React
const MyReactComponentFunctionReact: React.FC = (props: NumberPack) => {
console.log(props.num1); // This will log value 7
console.log(props.num2); // This will log value 10
return <div>I'm a div tag React</div>;
};Returning scenario (Functions/Functional Component related)
Now we know how to declare a function and also to pass props to a function. Let’s learn how to show the returning type in a TypeScript function or a functional component.
type NumberPack = {num1: number; num2: number};
const myFunction: Function = (props: NumberPack) => {
let addedNumber: number = 70;
addedNumber += props.num1; // addedNumber becomes 70 + 7 = 77 (number type)
addedNumber += props.num2; // addedNumber becomes 77 + 10 = 87 (number type)
return addedNumber // returns value 87 (number type)
};
myFunction(7, 10);Here you can see that this function is returning a number. So we can state this is returning a number type like this.
type NumberPack = {num1: number; num2: number};
const myFunction: Function = (props: NumberPack): number => {
let addedNumber: number = 70;
addedNumber += props.num1; // addedNumber becomes 70 + 7 = 77 (number type)
addedNumber += props.num2; // addedNumber becomes 77 + 10 = 87 (number type)
return addedNumber // returns value 87 (number type)
};
myFunction(7, 10);In return also we have to deal with not one variable we have to deal with multiple variables sometimes. Let's get an example. Let's say this is returning an object like in {nu1: number; nu2: number, nu3: number} type.
type NumberPack = {num1: number; num2: number};
type NumberPackExtended = {nu1: number; nu2: number; nu3: number};
const myFunction: Function = (props: NumberPack): NumberPackExtended => {
let addedNumber1: number = 70;
let addedNumber2: number = 70;
let addedNumber3: number = 70;
addedNumber1 += props.num1; // addedNumber1 becomes 70 + 7 = 77 (number type)
addedNumber2 += props.num2; // addedNumber2 becomes 70 + 10 = 80 (number type)
addedNumber3 -= props.num1; // addedNumber3 becomes 70 - 7 = 63 (number type)
return {nu1: addedNumber1, nu2: addedNumber2, nu3: addedNumber3}; // returns {nu1: 77, nu2: 80, nu3: 63}
};
myFunction(7, 10);If we talk about returning a functional component in React/React Native we just have to change the returning type to React.FC like this.
type NumberPack = {num1: number; num2: number};
// In React Native
const MyReactComponentFunctionReactNative: React.FC = (
props: NumberPack,
): React.JSX.Element => {
return (
<View>
<Text>{props.num1}</Text>
<Text>{props.num2}</Text>
</View>
);
};
// In React
const MyReactComponentFunctionReact: React.FC = (
props: NumberPack,
): React.JSX.Element => {
return (
<div>
<h1>{props.num1}</h1>
<h1>{props.num2}</h1>
</div>
);
};Summary of function/functional component creation
Here is the easy-to-understand template for creating a function/functional component creation.
const myFunction: type of myFunction = (
props: type of props
): type of returning variable or object => {};
Hooks declaration scenario (React/React Native ecosystem-related)
There are many hooks in React/React Native. In most of our projects, we use those hooks. Let’s find out how to properly declare a hook and assign it to that in TypeScript.
Let's get the useState hook which is commonly used in React/React Native projects. Let's say we have a component that increments by 1 when the user clicks a button. For that have to use the useState hook. Here is the code for that.
const [myNumber, setMyNumber] = useState<number>();
Let's say we have to keep a state object like in {num1: number; num2: number} . Here is how we can do that.
type NumberPack = {num1: number; num2: number};
const [myNumberGroup, setMyNumberGroup] = useState<NumberPack>();We can do this in another way.
const [myNumberGroup, setMyNumberGroup] = useState<{
num1: number;
num2: number;
}>();But I’m not recommending defining like this because it reduces the clarity of the code. For a reader or a newcomer/intern to the code be able to easily understand your code. So I prefer defining a type and then using that in the hook.
Tired! I know this is a long article about TypeScript syntaxes. But don't worry, you have the main idea of properly using typescript syntaxes. Also properly using TypeScript will give you these things.
- Provides compile-time type checking, reducing errors and improving code quality.
- Offers better tooling with features like code completion and refactoring tools, boosting developer productivity.
- Improves code readability and maintainability through clear type annotations and function signatures.
- Catches common errors during development, minimizing bugs and enhancing code robustness.
- Allows safer code refactoring by identifying all references and ensuring they are updated correctly.
Now you can write clean and good code :)
See you soon… Stay tuned! Stay happy! Stay healthy! Stay motivated! Please give a clap 👏🏻 if you like this article and also if it's useful. Also check out my other articles too. Thank you :)