Home > OS >  Typescript accept object parameter as long as it contains a key
Typescript accept object parameter as long as it contains a key

Time:02-25

I have a function that is shaped like:

type itemType = {
    id: string;
    [x: string]: unknown;
}
// my function
(item: itemType) => {do stuff here}

I want to use this function and pass an object that at least contains an id key, is there a way to do this? I am trying to do it this way but get errors:

type bigItemType = {
    id: string;
    name: string;
}
(item as bigItemType) => { console.log(item.name) }

I'm able to bypass it by casting it in the body of the function but is it possible to do it in the parameters?

error: Type 'bigItemType' provides no match for the signature '(item: itemType): void'

CodePudding user response:

I'm not sure if I understand your question correctly. But you can simply extend another type with & operator:

type itemType = {
    id: string;
    [x: string]: unknown;
}

type bigItemType = itemType & {
    name: string;
}

const func = (item: bigItemType) => { console.log(item.name) }

Now bigItemType extends itemType and adds name to it.

You can test it here.

CodePudding user response:

You can use an intersection and union:

type ItemType = { id: string; } | { id: string; } & { [key: string]: unknown; }

Explanation @ Tree of locations object type declaration

  • Related