2

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.

2
  • After reading the MDN for Object.assign more closer, it's first parameter isn't a callback function. I'm not sure what you are trying to achieve with it Commented Jun 3, 2017 at 7:32
  • 1
    @user2340824 functions can also be assigned with properties :). I wonder if { (a) => a, ...{x: 10} } wouldn't cut it? Commented Jun 3, 2017 at 7:50

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

No, there is not. Object spread syntax is part of object literals, which always create (non-function) Object objects.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.