如何让TypeScript类型同时接受title属性与四种调用签名之一?
实现兼具可选title与多函数签名的config属性
方案一:交叉类型(简洁直接)
函数在TypeScript里本质属于对象类型,直接把多函数签名的联合类型和带可选title的对象类型做交叉,就能让config同时具备函数调用能力和title属性。
import type { ReactNode } from 'react'; interface Props<T> { config: { title?: string; } & ( ((limitText: boolean, bold: boolean, content: ReactNode) => void) | ((iterable: boolean, content: T[], selector: string) => void) | ((markup: boolean, content: string) => void) | ((stack: boolean, coloredLevel?: boolean, content: string[]) => void) ); }
这样定义后,config既可以访问可选的title属性,又能以四种签名中的任意一种被调用。
方案二:可辨识联合类型(类型更明确)
如果需要更精准的类型区分,给每个配置类型添加唯一的辨识字段(比如type),组成可辨识联合类型,TypeScript能自动根据辨识字段做类型推断。
import type { ReactNode } from 'react'; // 基础配置,包含可选title type ConfigBase = { title?: string }; // 每种函数场景对应一个带辨识符的类型 type LimitTextConfig = ConfigBase & { type: 'limitText'; execute: (limitText: boolean, bold: boolean, content: ReactNode) => void; }; type IterableConfig<T> = ConfigBase & { type: 'iterable'; execute: (iterable: boolean, content: T[], selector: string) => void; }; type MarkupConfig = ConfigBase & { type: 'markup'; execute: (markup: boolean, content: string) => void; }; type StackConfig = ConfigBase & { type: 'stack'; execute: (stack: boolean, coloredLevel?: boolean, content: string[]) => void; }; // 组合成联合类型 type PropsConfig<T> = LimitTextConfig | IterableConfig<T> | MarkupConfig | StackConfig; interface Props<T> { config: PropsConfig<T>; }
使用时通过config.type就能区分不同配置类型,调用对应的execute方法,同时每个类型都保留了可选的title属性,适合复杂场景下的类型校验。
内容的提问来源于stack exchange,提问作者Alex Ironside
相关产品推荐
相关产品推荐

