如何实现带属性的TypeScript函数接口?含React场景示例
如何实现带额外属性的函数类型接口
你遇到的这种接口属于可调用对象类型——它既要求是一个符合特定签名的函数,同时还需要拥有指定的额外属性。React的FunctionComponent就是这种模式的典型应用:组件本身是渲染函数,同时可以挂载propTypes、defaultProps等静态属性。
实现Example<string>类型的test
这里提供两种无需单独命名函数的实现方式:
方式一:先定义匿名函数,再添加属性
直接创建匿名函数并赋值给test,之后为其添加name属性:
interface Example<T> { (a: T): T; name: T | undefined; } const test: Example<string> = (a) => a; test.name = "exampleName"; // 也可以设为 undefined
方式二:用Object.assign合并函数与属性
通过Object.assign将匿名函数和属性对象合并,一步完成赋值:
interface Example<T> { (a: T): T; name: T | undefined; } const test: Example<string> = Object.assign( (a: string) => a, { name: "exampleName" } );
对应React FunctionComponent的写法理解
React的函数组件本质也是这种可调用对象,比如你可以这样写:
import React from 'react'; const MyComponent: React.FunctionComponent<{ text?: string }> = ({ text }) => { return <div>{text}</div>; }; // 添加静态属性 MyComponent.defaultProps = { text: "默认内容" }; MyComponent.displayName = "MyComponent";
或者用Object.assign简化:
const MyComponent = Object.assign( ({ text }: { text?: string }) => <div>{text}</div>, { defaultProps: { text: "默认内容" }, displayName: "MyComponent" } ) as React.FunctionComponent<{ text?: string }>;
核心逻辑都是:函数本身作为一个对象,允许挂载额外的属性,TypeScript会严格校验函数签名和属性类型是否匹配接口定义。
内容的提问来源于stack exchange,提问作者Unknown developer
相关产品推荐
相关产品推荐

