Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
17
rated 0 times [  19] [ 2]  / answers: 1 / hits: 20791  / 7 Years ago, sun, november 12, 2017, 12:00:00

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?


More From » string

 Answers
6

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
}

[#55958] Wednesday, November 8, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ansleyk

Total Points: 42
Total Questions: 100
Total Answers: 83

Location: Angola
Member since Wed, Apr 13, 2022
2 Years ago
;