TypeScript
union props & type guard
将 props extends Record<string, unknown> 再实现基于 Record<string, unknown> 的谓语函数,可以获得正确的分支守卫。
export interface SourceBasicProps extends Record<string, unknown> {isDropped?: boolean;}interface StorageSource extends SourceBasicProps {type: 'input' | 'output';item: Storage;}interface OperatorSource extends SourceBasicProps {type: 'field_operator' | 'table_operator';item: OperatorComponent;}export function isStorageSource(a: Record<string, unknown>,): a is StorageSource {return !!('type' in a && (a.type === 'input' || a.type === 'output'));}
关键点在于将 Props 的基底类型先收缩到 Record<string, unknown> ,在未收缩的类型上(unknown 或 object),谓语函数无法实现,或实现较为繁琐,原理未知。
