TypeScript

union props & type guard

props extends Record<string, unknown> 再实现基于 Record<string, unknown> 的谓语函数,可以获得正确的分支守卫。

  1. export interface SourceBasicProps extends Record<string, unknown> {
  2. isDropped?: boolean;
  3. }
  4. interface StorageSource extends SourceBasicProps {
  5. type: 'input' | 'output';
  6. item: Storage;
  7. }
  8. interface OperatorSource extends SourceBasicProps {
  9. type: 'field_operator' | 'table_operator';
  10. item: OperatorComponent;
  11. }
  12. export function isStorageSource(
  13. a: Record<string, unknown>,
  14. ): a is StorageSource {
  15. return !!('type' in a && (a.type === 'input' || a.type === 'output'));
  16. }

关键点在于将 Props 的基底类型先收缩到 Record<string, unknown> ,在未收缩的类型上(unknown 或 object),谓语函数无法实现,或实现较为繁琐,原理未知。