Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 396
the_lrner Avatar asked Nov 12 '17 17:11

the_lrner


People also ask

What does Keyof do in TypeScript?

keyof takes an object type and returns a type that accepts any of the object's keys.

Should object keys be strings?

Object keys can only be strings, and even though a developer can use other data types to set an object key, JavaScript automatically converts keys to a string a value.

How do you handle an object in TypeScript?

Syntax. var object_name = { key1: “value1”, //scalar value key2: “value”, key3: function() { //functions }, key4:[“content1”, “content2”] //collection }; As shown above, an object can contain scalar values, functions and structures like arrays and tuples.

What is key string in TypeScript?

The {[key: string]: string} syntax is an index signature in TypeScript and is used when we don't know all the names of a type's properties ahead of time, but know the shape of the values. The index signature in the examples means that when an the object is indexed with a string , it will return a string .


1 Answers

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
}
like image 145
user184994 Avatar answered Oct 05 '22 06:10

user184994