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?
keyof takes an object type and returns a type that accepts any of the object's keys.
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.
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.
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 .
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With