How to type an object key in Typescript?

Viewed 1771

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.

2 Answers

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

try this :

type DataType = "about" | "favorites" | "username";
type Expand<U> = U extends string ? { [key in U]: any } : never

type UpdatedData = Expand<DataType>

TS Playground

Related