Typing it out...
Tags: typescript, webdev, beginners, programming
Published: 2023-06-06 18:45:28

 [Find part 1 here](https://dev.to/bealecs/type-it-out-4jae)
### [Part 2]: We know what it is and when to apply it, but how do we actually implement _TypeScript_?

In [part one](https://dev.to/bealecs/type-it-out-4jae), I discussed how **TypeScript** is defined and when it may be **useful**… In this article, I am going to dive a little deeper into **TypeScript** and provide some good examples of setting/using **types** & **interfaces**.

Jump to Section

- [Section 1 - Getting Started](#section-1)

- [Section 2 - Interface & Type](#section-2)

- [Section 3 - Personal Examples Utilizing TypeScript](#section-3)

- [Section 4 - Recommended Resources](#section-4)

<br />
#### Getting Started
<a id="section-1"></a>
**TypeScript** is considered a [dev dependency](https://docs.npmjs.com/cli/v9/configuring-npm/package-json#devdependencies), which means that (if you are going to use it) you only need it in the **development** environment. Upon build, the **TypeScript** is compiled to **JavaScript** and so it is not a necessary dependency. 

With that being said we can open up our project terminal and run :

```
npm install typescript --save-dev
```
(FYI: The --save-dev flag on the npm install command saves the package as a **dev dependency**)

<hr />
#### Interface & Type
<a id="section-2"></a>
Now that we have **TypeScript** installed, we are ready to get into the fun stuff - defining our **types**, and leading ourselves to a **safer** development environment.

How can we start to define **types** though? In [part one](https://dev.to/bealecs/type-it-out-4jae), there was an example : 

```
interface Person {
name: string,
age: number
}
const person: Person = {
name: "Clif",
age: 24
}
```
but this code probably doesn't look familiar. What is an **Interface**?

 According to [Tutorials Point](https://www.tutorialspoint.com/typescript/typescript_interfaces.htm#:~:text=An%20interface%20is%20a%20syntactical,the%20declaration%20of%20the%20members.), an **interface** is a syntactical contract that an entity should conform to. In other words, an **interface** defines the _syntax_ that any entity must adhere to.

Without **TypeScript**, the following code still **works**:

```
function Person(first, age) {
  this.firstName = first;
  this.age = age;
}

const person = new Person("Clif", 24);
```
to construct a new object variable named person that looks like this :

```
const person = {
    firstName: "Clif",
    age: 24
}
```
The problem with this, mostly if left to user input, is that **any data type** would pass as parameters. For example :

*Note: there are ways to ensure this doesn't happen, like client-side form validation, but for the sake of this article I am using TypeScript*
```
const person = new Person(24, "Clif");
console.log(person);
//The logged value would read { firstName: 24, age: "Clif" }
```
Finally, enter **interfaces** & **type** layouts. With **TypeScript** we can alter the code to be as follows:

```
interface User {
    firstName: string;
    age: number;
}

const user: User = {
    firstName: "Clif",
    age: 24,
};
```
With this example, you are setting the new variable (user) to be of the new **type** we created with the **interface** above. This means that the values passed to the _firstName_ and _age_ properties must be a **string** and a **number**, respectively. 

**Failure to provide an accurate data type as input will provide a type error to the console**, thus making errors more easily identifiable/fixable. 

<hr />
#### Personal Examples Utilizing TypeScript
<a id="section-3"></a>
A problem that I have sometimes when I am learning is that I need to see **practical, real-world** applications to things in order to really _absorb_ them.

With that being said, I am going to provide some use cases that I have found for **TypeScript**, and why I implemented it below:

I have a component below that I was passing props to: a **string** that was holding a state value, and a **function** that was changing the value of the state on the click of a button from the component receiving the props. 

layout.tsx :
```
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const [theme, setTheme] = useState("light"); //theme prop

  const onThemeChange = () => {
    setTheme((prevTheme) => (prevTheme !== "dark" ? "dark" : "light"));
  }; //handler prop

  return (
    <html lang="en">
      <body className={"container_" + theme}>
//props passed to nav component here
        <Navigation theme={theme} handler={onThemeChange} /> 
        {children}
      </body>
    </html>
  );
}
```
 Navigation.tsx :

```
/* alternatively could do :
interface Props {
  theme: string;
  handler: () => void;
} */

type Props = { 
  theme: string;
  handler: () => void;
};

//Check parameters to see type declaration
export const Navigation = (props: Props) => {

const themeClicker = () => {
    props.handler();
 } //this method catches the function to serve it to the onClick 
   //attribute of the list element in the JSX

return (
//JSX HERE
<li className={NavigationStyles.themer} id="themer" onClick={themeClicker}>
)};
```
In the above example, I utilized **type layout** to create a new **type value** 'Props'. Props expects two properties, theme & handler. Theme would need to be used as a **string value** as it is representing the state, and handler needs to be used as a **void function** that gets called on click of a button.

You can see the state and function values that were passed as props to the Navigation component, and they were later used in my Navigation component to render state between dark/light mode. *I am not pasting my full Navigation component code as it is hefty, please view the [github repo](https://github.com/Vets-Who-Code/js-web-path-bealecs) if interested in viewing the full source code*

The Navigation component was expecting props as passed in the parameter, but specifically was expecting props of values: **string and function**. 

*If interested, checkout out [the differences between using interface vs type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces)*


![Teammates giving each other a high five at their computers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cs93dgttwlaat8snys6b.jpg)

<hr />
#### Recommended Resources
<a id="section-4"></a>
- [TypeScript Docs for JS programmers]
(https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html)

- [TypeScript Docs for beginners]
(https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html)

- [Type vs Interface]
(https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces)

- [Dev dependency vs dependency]
(https://stackoverflow.com/questions/18875674/whats-the-difference-between-dependencies-devdependencies-and-peerdependencie)

- [NPM Docs - dev dependencies]
(https://docs.npmjs.com/cli/v9/configuring-npm/package-json#devdependencies)

#### Special shoutout:

- [CodePen](https://codepen.io/) - I have been using this site 
lately for remote environment coding if I just wanted to try out some code on the fly with little to no commitment.

I highly recommend checking it out if you haven't used it before, it is very handy.