Use object spread operator to construct function object with fields

我的梦境 提交于 2019-12-24 01:26:05

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/44341426/use-object-spread-operator-to-construct-function-object-with-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!