DEV Community

Cover image for Typing it out...
Clifton Beale
Clifton Beale

Posted on

Typing it out...

Find part 1 here

[Part 2]: We know what it is and when to apply it, but how do we actually implement TypeScript?

In part one, 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

Getting Started


TypeScript is considered a dev dependency, 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
Enter fullscreen mode Exit fullscreen mode

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


Interface & Type


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, there was an example :

interface Person {
name: string,
age: number
}
const person: Person = {
name: "Clif",
age: 24
}
Enter fullscreen mode Exit fullscreen mode

but this code probably doesn't look familiar. What is an Interface?

According to Tutorials Point, 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);
Enter fullscreen mode Exit fullscreen mode

to construct a new object variable named person that looks like this :

const person = {
    firstName: "Clif",
    age: 24
}
Enter fullscreen mode Exit fullscreen mode

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" }
Enter fullscreen mode Exit fullscreen mode

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,
};
Enter fullscreen mode Exit fullscreen mode

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.


Personal Examples Utilizing TypeScript


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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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}>
)};
Enter fullscreen mode Exit fullscreen mode

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 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

Teammates giving each other a high five at their computers


Recommended Resources

Special shoutout:

  • CodePen - 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.

Top comments (0)