hrgui
8/25/2022

The road to becoming a TypeScript Ninja: JSON, keyof, typeof

Just recently I read TypeScript is terrible for library developers. I am not a library developer. The TypeScript I write is more of an app developer. I consume libraries, and I use them. I don’t feel the pain, but I think I should to understand TypeScript like a ninja.

Today I learned TypeScript knows how to import JSON files.

This was introduced in TypeScript 2.9+. TypeScript is now at 4.7. I feel my knowledge of TypeScript is antiquated… but that’s okay. I am ready to learn.

To import a JSON file, the tsconfig.json must have the following:

"resolveJsonModule": true
{
  "a": "apple",
  "b": "boy",
  "c": "cat"
}
import messages from "./i18n.json";

messages.a; // doesn't
messages.e; // would error

This can be useful for dealing with static i18n files - local. I believe we can then type our component in a certain way!

import React from "react";
import messages from "./i18n.json";

type Props = {
  i18nKey: keyof typeof messages;
};

const Trans = ({ i18nKey }: Props) => {
  return <div>{messages[i18nKey]}</div>;
};

const App = () => {
  return <Trans i18nKey="d" />; // errors because d is not part of messages
};

export default Trans;

Woah, hold up, what’s typeof?

typeof only works in TS files, not .d.ts files. This takes in any JavaScript type and runs type inference for it.

So…

type Messages = typeof messages;

becomes…

type Messages = {
  a: string;
  b: string;
  c: string;
};

OK, what about keyof?

If I just want the keys, then… how does that work? We can use keyof:

The keyof operator takes an object type and produces a string or numeric literal union of its keys.

So in the case above:

type MessageKeys = typeof keyof messages;

is now the same as

type MessageKeys = "a" | "b" | "c";

But I have my own object though!

That’s where it gets tricky. Not sure how that would work. If I find something, or if anyone finds something, would love to know!

hrgui

Harman Goei (hrgui) is a developer that loves to make cool and awesome web applications. His strength is in HTML, CSS, JavaScript, but he is willing to code anywhere in the stack to make the web be awesome.

© 2024 Harman Goei