Home > Net >  Allow only keys from array and make it optional
Allow only keys from array and make it optional

Time:07-30

I'm trying to learn TypeScript and here's the problem: I have exported the constant of ROUTES:

export const ROUTES: Array<string> = ["USD", "EUR", "PLN"];

And I want to create the Rate type. It should be the object with one or more keys that are in the ROUTES array.

const rate : Rate = { // Error
    USD: 1, // ALLOW
    PLN: 2, // ALLOW
    EUR: 12, // ALLOW
    BTC: 2222 // DENY
}

OR

const rate : Rate = { // No error
    USD: 1, // ALLOW
    EUR: 12 // ALLOW
}

What I've tried:

import { ROUTES }  from "../constants";

type Rate = {
    [K in typeof ROUTES[number]]: number
}

AND

import { ROUTES }  from "../constants";

const allowedKeys1 = [...ROUTES] as const;
const allowedKeys2 = ["USD", "EUR", "PLN"] as const;

type Rate = {
    [K in typeof allowedKeys[1 | 2][number]]: number
}

Notice that allowedKeys2 and allowedKeys2 are different and give diffenet effects. allowedKeys1 does nothing and allowedKeys2 forces to use all keys, but doesn't use imported array. Using directly ROUTES is the same as using allowedKeys1.

CodePudding user response:

You seem to already know that as const plays a role here. Without as const, the information about specific array elements is lost at assignment.

Now you can use a simple partial Record type.

export const ROUTES = ["USD", "EUR", "PLN"] as const;

type Rate = Partial<Record<typeof ROUTES[number], number>>

Playground

  • Related