DEV Community

Cover image for TS Part 2: Getting Started with TypeScript
Samuel Littell
Samuel Littell

Posted on

TS Part 2: Getting Started with TypeScript

So in my previous post we learned a little bit about the background, history, and purposes of TypeScript and how it could potentially be used, or not used, for your application's development. Now I want take a look at some of the basic TypeScript fundamentals and how to get started using TypeScript in your React or JavaScript projects.

Image description

First, a simple way to initialize a new React project with TypeScript is to utilize npx create-react-app my-app but with --template typescript following it. So simply pop open your terminal, set it to the desired directory, and input the command: npx create-react-app my-app --template typescript. So now, you will have initialized a new React app set-up with all of the TypeScript dependencies needed for your project. Immediately upon opening your "my-app" directory in your source-code editor, the first thing you'll notice is that all your files are now followed by the .tsx extension, as opposed to .jsx. But, if you already have a React project in progress, you can add TypeScript by installing it with the command: npm install --save typescript @types/node @types/react @types/react-dom @types/jest.

Image description

If you're not using React and want to implement TypeScript in your JavaScript/HTML project, you'll need to first run the command npm init -y which will load your package.json file with your dependencies and scripts inside. Now, simply install TypeScript with the command npm i --save-dev typescript. You should now see TypeScript loaded into your dev-dependency list, which we put there since TypeScript is not required for production. On top of this you will need to load your tsconfig.json file which will contain a boiler-plate list of default TypeScript properties which are either commented out or uncommented. Simply uncomment out any other properties to activate them. To load the config file use the command: npx tsc --init. Lastly, there are multiple options to compile your TypeScript code into JavaScript, and to bundle your files, but in order keep this short, I would highly recommend researching those options on your own, and see what is best suited for the application you're developing. (Snowpack apparently has a very quick/easy set-up for TypeScript Applications.)

Image description

In my previous TypeScript post we quickly took a look at some of the very basic typing, such as string, number, and boolean. But what if we need to type something a bit more complex, such as an array? Or what happens if an array needs to contain multiple types?

To type an array we need to first declare our variable and assign it a type. This can be any type, but in order to apply it to an array, it needs to be followed by square brackets, giving you something like this:

// Declaration
let arrayStr: string[];
let arrayNum: number[];
let arrayBool: boolean[];

// Initialization
arrayStr = ['Apple', 'Orange', 'Banana'];
arrayNum = [1, 2, 3, 4];
arrayBool = [true, false];

// TypeError: 'string' is not assignable to type 'number'.
arrayNum = [1, 2, 3, '4'];
Enter fullscreen mode Exit fullscreen mode

or using generic array type syntax in your declaration is another option:

// Declaration
let arrayStr: Array<string>;
let arrayNum: Array<number>;
let arrayBool: Array<boolean>;

// Initialization
arrayStr = ['Apple', 'Orange', 'Banana'];
arrayNum = [1, 2, 3, 4];
arrayBool = [true, false];

// TypeError: 'string' is not assignable to type 'number'.
arrayNum = [1, 2, 3, '4'];

Enter fullscreen mode Exit fullscreen mode

Image description

Now, if we want our array to contain different types, we can utilize what TypeScript calls a Tuple. A tuple can contain multiple types of data. To achieve this we simply declare our types wrapped in square brackets, then initialize with the corresponding values, like so:

// Declaration
let tuple: [number, string, boolean];

// Initialization
tuple = [1, "opSpark", true];

// TypeError: Type 'number' is not assignable to type 'string'.
tuple = [1, 4, true];
Enter fullscreen mode Exit fullscreen mode

or if we need to wrap our tuple into an array, try this:

// Declaration
let tupleArr: [number, string][];

// Initialization
tupleArr = [[1, 'Sam'], [2, 'Student'], [3, 'opSpark']];

// TypeError: Type 'boolean' is not assignable to type 'string'.
tupleArr = [[1, 'Sam'], [2, 'Student'], [3, false]];
Enter fullscreen mode Exit fullscreen mode

Image description

Finally, let's take a look at objects. Objects are fundamental to the way we move and group data in JavaScript. So, how can we define an object using TypeScript? There are actually two ways to declare an object, and the first really isn't recommended. Let's take a look at this:

// Declaration
let anObject: Object;
Enter fullscreen mode Exit fullscreen mode

So this is a completely valid way to define an object in TypeScript, but an object can have a lot of different properties inside of it. So how can we validate that the object we are trying to utilize contains the corresponding set of types? Well, TypeScript provides us with a type keyword. To use these just start with the type keyword followed by the name or "alias" of your object. By utilizing objects in TypeScript not only can we assure that the correct type is being used, but also catch missing properties, check it out:

// Create type alias
type Object = {
  name: String;
  age: Number;
};

// Initialize / Declare an object with new type created
let anObject: Object = {
  name: 'Sam',
  age: 35
};

// TypeError: Property 'age' is missing in type 
// '{ name: string; }' but required in type 'Object'. 
let anObject: Object = {
  name: 'Sam',
};

// TypeError: Type 'string' is not assignable to type 'Number'. 
let anObject: Object = {
  name: 'Sam',
  age: '35'
};
Enter fullscreen mode Exit fullscreen mode

So there you have it! I hope this was helpful and shows how catching type errors at the time of compile, and not later at runtime, can be super helpful and an efficient way of correcting your code. Hopefully TypeScript can become an important part of your workflow. Happy coding!

Top comments (0)