34

I want to create an object of type Partial, where the keys will be some combination of 'a', 'b', or 'c'. It will not have all 3 keys (edit: but it will at least have one). How do I enforce this in Typescript? Here's more details:

// I have this:
type Keys = 'a' | 'b' | 'c'

// What i want to compile:
let partial: Partial = {'a': true}
let anotherPartial: Partial = {'b': true, 'c': false}

// This requires every key:
type Partial = {
  [key in Keys]: boolean;
}

// This throws Typescript errors, says keys must be strings:
interface Partial = {
  [key: Keys]: boolean;
}

The two methods I've tried above (using mapped types and interfaces) don't achieve what I want. Can anyone help here?

the_lrner
  • 575
  • 1
  • 5
  • 11

2 Answers2

54

You can use the ? to make the keys optional, so

interface Partial {
   a?: boolean;
   b?: boolean;
   c?: boolean;
}

Or, you can do this:

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

type Test = {
    [K in Keys]?: boolean
}
user184994
  • 17,791
  • 1
  • 46
  • 52
1

Another way to do this is...

// I have these keys
type Keys = 'a' | 'b' | 'c'

// This type requires every key:
type WithAllKeys = {
  [key in Keys]: boolean;
}

// This will have a Partial key
interface WithPartialKeys: Partial<WithAllKeys>;
Martin
  • 161
  • 1
  • 6