javascript - 如何让扩展运算符只枚举非函数属性?
技术栈:ReactJS 16.x,Typescript 2.8.1,create-react-app 项目。
当我使用展开运算符将 props 从 TypeScript 类传递给 React 组件时,我遇到了类型错误。
该错误仅在类中定义了函数时发生。如果类中有一个函数表达式变量,展开运算符工作正常。我相信这与类上属性的枚举有关。因此,我使用装饰器将函数标记为不可枚举,但仍然出现相同的错误。下面是代码:
`Message` 是我正在尝试传播到 React 组件中的类。
export class Message {
constructor() {
this.init2 = (msg: string) => {
this.msg = 'init2';
return this;
}
}
public msg: string;
// This works with spread operator
public init2: (msg: string) => Message;
// This will cause the spread operator to fail
public init(msg: string): Message {
this.msg = msg;
return this;
}
// Even with decorator to turn off enumeration, spread operator fails
@enumerable(false)
public initNoEnum(msg: string): Message {
this.msg = msg;
return this;
}
}
ReactJS 组件,其属性被定义为 Message:
export class MessageComponent extends React.Component<Message, any>{
render() {
return (<div>{this.props.msg}</div>);
}
}
使用 MessageComponent 的渲染方法:
public render() {
const msg = new Message().init('hello world!');
return <MessageComponent {...msg} /> // The spread here fails
}
enumerable 装饰器函数:
export function enumerable(value: boolean): any {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
descriptor.enumerable = value;
};
}
tsconfig:
"compilerOptions": {
"outDir": "./build",
"module": "esnext",
"target": "es5",
"lib": [ "es6", "dom" ],
"sourceMap": true,
"allowJs": true,
"jsx": "react",
"moduleResolution": "node",
"rootDir": "src",
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true,
"experimentalDecorators": true
},
如果我注释掉 init 和 initNoEnum,并保留 init2,展开运算符就可以工作。使用 init 和 initNoEnum 时,展开运算符会失败,并显示类似的消息:
类型 '{ msg: string; init2: (msg: string) => Message; }' 不能分配给类型 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{ children?: ReactNode ...'。类型 '{ msg: string; init2: (msg: string) => Message; }' 不能分配给类型 'Readonly'。类型 '{ msg: string; init2: (msg: string) => Message; }' 中缺少属性 'init'。
我做错了什么?我如何才能让展开运算符只枚举属性而不是函数?
答案#1
为什么要使用装饰器,而你自己就可以直接删除函数
默认情况下,你不能使用展开运算符仅获取非函数属性,因为函数也是属性,但也许通过你的 tsconfig 设置它应该可以工作,不过,你可以先修改传递给展开运算符的对象。
要使用扩展语法仅获取非函数属性而不依赖 tsconfig 的魔法,我建议使用一个函数来过滤掉函数属性,然后像这样使用扩展运算符:
const filterOutFunctions = object => {
return Object.keys(object)
.filter(key => typeof(object[key]) !== 'function')
.reduce((filteredObj, currentItem) => {
filteredObj[currentItem] = object[currentItem]
return filteredObj
}, {})
}
const objectWithFunctions = {
aFunction() {},
aProperty: 'A good ol string'
}
// Now you can do spread operator stuff with a filtered version like so:
{...filterOutFunctions(objectWithFunctions)}
// returns: { aProperty: 'A good ol string' }
这个方法的工作原理是通过使用 .filter 遍历 object 的 keys 来过滤出指向函数的键。然后我们通过使用 .reduce 将所有剩余的属性分配到一个新的空对象中来收集它们。
