Deriving Types From Values 15 exercises

No Creating Runtime Values from Types

In TypeScript, it's possible to create types from values using the typeof keyword.

For example, here we have a user with an id number and name string. Then we create a type from that value:

const user = {
id: 1,
name: "Waqas",
type UserFromValue = typeof user;


Loading explainer


00:00 We've been talking here, like with typeof, is that you can create types from values. So we have a user type here, which is inferred as ID number and name string, and then we can create a type from that, user from value, ID number and name string. Really cool. But then why can't we go the other way?

00:18 Why can't we say, so why not create values from types? Let's say we have a user interface here. Can we not say, like, user is value of user or something like that? Turn it directly into a runtime type or a runtime value? Well, if you think about it, this would go against something that TypeScript is trying to do.

00:38 TypeScript is really trying not to interfere at runtime. We looked at this when we looked at the TypeScript-only features. They added classes, sure, but they eventually got adopted into JavaScript. They added eons, fine, like a sort of little bit of syntax sugar on top, really, of the way that JavaScript works.

00:57 And they added a couple of other things too, and I don't think they would do that today. This would be a big break from what TypeScript has done before, right? They don't tend to, like, this would need an enormous amount of code, and that code would not be particularly predictable. How would you know what number you wanted to generate? How would you know what string you wanted to generate?

01:16 So basically, you can't do this in TypeScript. You can derive types from values, but you can't create values from types. I think there are a couple of experimental code generation stuff that I've seen a while ago, but I don't think they're particularly production-ready.

01:35 And there are, of course, other scripts that you can use to take types and turn them into, like, example JSON. Faker is a great example of that that comes to mind, a really great library that lets you just mock up mock data from just schemas, not necessarily even types.

01:53 But it goes against a fundamental idea in TypeScript to be able to let you do this. So you can create types from values, but not values from types.