Search code examples
javascripttypescriptecmascript-next

Use object spread operator to construct function object with fields


I have successfully created a function object with additional fields using the following Object.assign:

Object.assign((a) => {
        // Do something....
    }, {
        x: 10
    })

... by following a discussion on typescript interfaces: Implementing TypeScript interface with bare function signature plus other fields

However, I find the Object.assign syntax hard to read, is there an object spread operator way of doing this?

Simply putting the function and object in curly brackets with two spreads does not seem to cut it:

{...(a) => a, ...{x: 10}}

It gives an error in Typescript and seems to skip the function signature runtime.

EDIT:

Basically I want to do the following (using typescript type-markup):

interface IFunc {(a) : string}
interface IStruct {x: number}
type IInteresting = IFunc & IStruct

Using @icepickle 's approach of {(a) => a, ...{x: 'y'}} just gives tons of errors. Seems I have to force cast the instance into the target type and then assign the property mutation style.


Solution

  • This is not possible, because when you use spread properties, the result will always be a plain object. For example, if you take a Date object and try to assign additional properties to it, you'll get a plain object instead of a Date object.

    console.log({ ...new Date(), x: 10 } instanceof Date); // false
    

    Try this in Babel REPL.