Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  120] [ 5]  / answers: 1 / hits: 5103  / 3 Years ago, sat, february 6, 2021, 12:00:00

I have a simple function that takes an object in parameter. In order to receive only valid data, I need to type the key of the object as such:




type DataType = about | favorites | username;
type UpdatedData = { [key in DataType]: any };

function onSave (updatedData: UpdatedData){
//do stuff
}

// in a component
const onClickSave = () => onSave({ about: text });




Typescript throws the following error:



Argument of type '{ about: text; }' is not assignable to parameter of type 'UpdatedData'.
Type '{ about: text; }' is missing the following properties from type 'UpdatedData': favorites, username



How to fix this? Of course, I could write [key: string] instead of [key in DataType] but the typing would be useless then.


More From » reactjs

 Answers
5

As the properties of UpdatedData can be optional just add in a ? to make them optional.


Edit:
As @Jérémie B mentioned an empty {} is still permitted with this.


type DataType = "about" | "favorites" | "username";
type UpdatedData = { [key in DataType]?: any };
function onSave (updatedData: UpdatedData){
}
const text = "hello"

const onClickSave = () => onSave({ "about": text });

[#1832] Sunday, January 31, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austynp

Total Points: 505
Total Questions: 118
Total Answers: 106

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
;