How to define a Record with a union as keys but have optional keys too?
Asked Answered
D

2

7

This is my dictionary:

type Words = 'man' | 'sun' | 'person'
type Dictionary = Record<Words,string>

And Dictionary equals to this type:

type Dictionary = {
    man: string;
    sun: string;
    person: string;
}

The goal is that other programmers know witch words should be added to the dictionary using IDE autocompletion. But it restrict them adding other optional words. I tried this but the result does not include words at all:

type Words = 'man' | 'sun' | 'person' | string
type Dictionary = Record<Words,string>
// Equals to 
type Dictionary = {
    [x: string]: string;
}

How can I have autocomplete with words but can have optional words too?

Dday answered 21/11, 2021 at 3:28 Comment(0)
T
15

You could use Partial utility type to preserve the power of generic type declaration and not have all the keys required.

type Dictionary = {
  man: string;
  sun: string;
  person: string;
  word: Partial<Record<Words, string>>;
};

I realize the question is quite old, but it is the top result while searching some of the variants of this problem so I think adding this here is appropriate.

Tetrachord answered 1/8, 2022 at 15:1 Comment(2)
With this solution I have to duplicate all words in the dictionary too!Dday
interface SourceDictionary { man: string; sun: string; person: string; } type Dictionary = SourceDictionary & Record<string, string>; Must've misunderstood your question. Does that help?Tetrachord
D
1

A solution is defining dictionary explicitly not using Record and Union types. just like this:

type Dictionary = {
  man: string;
  sun: string;
  person: string;
  [word:string]:string;
}
Dday answered 21/11, 2021 at 3:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.