Deriving Types From Values 15 exercises
explainer

Using the Same Name for Values and Types in TypeScript

We've talked about how various things in TypeScript cross the boundaries between the value world and the type world. You can do a similar thing yourself.

Consider the following Logger constant, and note the capital "L":


export const Logger = {
log: (message: string) => {
console.log(me

Loading explainer

Transcript

00:00 We've talked about how various things in TypeScript cross the boundaries between the value and the type world. Well you can kind of do the same thing yourself. Let's say that we have this const logger here. Notice that I'm specifying logger with an uppercase L here. And we have an object here with a bunch of different things on it. So log, info, warn, error. You could imagine

00:19 that this is like an abstracted piece of something that I want to then later inject into my app. Let's say that sometimes I want my logger to be like something that logs to an external service. Sometimes I just want to log to the console. Sometimes I don't want to log at all for tests

00:35 or something. And then at the bottom we say export type logger equals type of logger. We're using type of to basically say okay this logger essentially has the same type as the logger const at the top. And I'm saying export type logger and we have export const logger. This

00:53 means we're exporting two things with the same name. If we look here at the second explainer we can see that we then import logger. We've actually got an alias here. We've got two things. We've got a type and we've got a const. This means that inside my function, let's say which

01:10 is called my app, we have my app logger and we're able to use it as the type here. But then later we're able to parse it as the actual logger down the bottom. So this is kind of doing double duty. It's like an alias here. So we have on one side we can use it as a type and on the other side we

01:28 can use it as a value. This is really good for when you have situations in your app where you have let's say you're doing Zod schemas for instance. You can like just create the schema itself and then later create a type out of the schema and then export it with the same name.

01:44 This gives you a lot of flexibility when you kind of have things that feel like types in your application and you want to reuse them as kind of the same thing. But I wanted to point this out because it's a really cool little technique to know about and it can sometimes just mean that you've got things in your app that feel like types and you want to be able to use them as

02:04 types or they feel like classes let's say and you want to be able to use them that way. Really,