Is it possible to partially define an object type?

Viewed 44

I have something to the effect of

function(param1, { knownParam1, ...opts })

I would like to type it to at least describe param1 and knownParam1. I'm thinking something like:

type Param2 = {
   knownParam1: string,
   ...otherParams: any
}
type Parameters = {
   param1: string
   param2: Param2
}

Is this sort of concept supported by TypeScript? I have a feeling it's not since destructuring is a bit of a new concept.

1 Answers

Yes you can achieve what you are looking for with something like:

type Param2 = { 
    knownParam: string;
    [key: string]: unknown;
}

function myFn(param1: string, param2: Param2) {
    const {
         knownParam,
         ...opts
    } = param2;

    // ...
}

The type of param two is an object with any known properties intersected with any other properties of unknown type.

Related