the_lrner
the_lrner

Reputation: 655

Typescript object: How do I restrict the keys to specific strings?

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?

Upvotes: 42

Views: 34488

Answers (2)

Martin
Martin

Reputation: 191

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>;

Upvotes: 4

user184994
user184994

Reputation: 18271

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
}

Upvotes: 66

Related Questions