From d8fdfd0c35af1935579a13791f428a858678e4a7 Mon Sep 17 00:00:00 2001 From: Hirahara Date: Tue, 10 Nov 2026 13:40:51 +0900 Subject: [PATCH] feat: extract props from TypeScript Pick and Omit --- .changeset/ts-pick-omit-props.md | 7 + .../__tests__/codeTypeHandler-test.ts | 139 ++++++++++++++++++ .../react-docgen/src/utils/getTSPickOrOmit.ts | 78 ++++++++++ .../src/utils/getTypeFromReactComponent.ts | 127 +++++++++++++++- .../src/utils/resolveGenericTypeAnnotation.ts | 7 + 5 files changed, 355 insertions(+), 3 deletions(-) create mode 100644 .changeset/ts-pick-omit-props.md create mode 100644 packages/react-docgen/src/utils/getTSPickOrOmit.ts diff --git a/.changeset/ts-pick-omit-props.md b/.changeset/ts-pick-omit-props.md new file mode 100644 index 00000000000..7d77b93f2fd --- /dev/null +++ b/.changeset/ts-pick-omit-props.md @@ -0,0 +1,7 @@ +--- +'react-docgen': minor +--- + +Extract props from the TypeScript `Pick` and `Omit` utility types +when the keys are string or number literals, including in type aliases, +intersections and interface `extends`. diff --git a/packages/react-docgen/src/handlers/__tests__/codeTypeHandler-test.ts b/packages/react-docgen/src/handlers/__tests__/codeTypeHandler-test.ts index 7ab08002b57..0c1b4cb56d6 100644 --- a/packages/react-docgen/src/handlers/__tests__/codeTypeHandler-test.ts +++ b/packages/react-docgen/src/handlers/__tests__/codeTypeHandler-test.ts @@ -263,6 +263,145 @@ describe('codeTypeHandler', () => { expect(Object.keys(documentation.descriptors)).toEqual(['b', 'a']); }); + describe('Pick and Omit', () => { + function getPropNames(code: string): string[] { + const definition = parseTypescript + .statement(code) + .get('expression') as NodePath; + + codeTypeHandler(documentation, definition); + + return Object.keys(documentation.descriptors); + } + + test('picks props', () => { + expect( + getPropNames( + `(props: Pick) => null; + interface Props { a: string; b: number; c: boolean }`, + ), + ).toEqual(['a', 'b']); + }); + + test('omits props', () => { + expect( + getPropNames( + `(props: Omit) => null; + interface Props { a: string; b: number; c: boolean }`, + ), + ).toEqual(['a', 'c']); + }); + + test('reads the docs of picked props', () => { + getPropNames( + `(props: Pick) => null; + interface Props { + /** The a prop */ + a?: string; + b: number; + }`, + ); + + expect(documentation.descriptors).toEqual({ + a: { + required: false, + tsType: { name: 'string' }, + description: 'The a prop', + }, + }); + }); + + test('supports Pick and Omit in type aliases and intersections', () => { + expect( + getPropNames( + `(props: Props) => null; + interface Base { a: string; b: number; c: boolean } + type Props = Omit & { d: string };`, + ), + ).toEqual(['a', 'b', 'd']); + }); + + test('supports Pick and Omit in interface extends', () => { + expect( + getPropNames( + `(props: Props) => null; + interface Base { a: string; b: number } + interface Props extends Pick { c: boolean }`, + ), + ).toEqual(['a', 'c']); + expect(documentation.composes).toEqual([]); + }); + + test('supports nested Pick and Omit', () => { + expect( + getPropNames( + `(props: Omit, 'b'>) => null; + interface Base { a: string; b: number; c: boolean }`, + ), + ).toEqual(['a']); + }); + + test('reads a type again when it is used twice', () => { + expect( + getPropNames( + `(props: Pick & Omit) => null; + interface Base { a: string; b: number }`, + ), + ).toEqual(['a', 'b']); + }); + + test('handles a Pick of the type that extends it', () => { + expect( + getPropNames( + `(props: A) => null; + interface A extends Pick { a: string; b: number }`, + ), + ).toEqual(['a', 'b']); + }); + + test('binds type arguments of the picked type', () => { + getPropNames( + `(props: Props) => null; + interface Base { value: T; other: number } + interface Props extends Pick, 'value'> {}`, + ); + + expect(documentation.descriptors).toEqual({ + value: { required: true, tsType: { name: 'string' }, description: '' }, + }); + }); + + test('supports number keys', () => { + expect( + getPropNames( + `(props: Omit) => null; + interface Props { 0: string; a: number }`, + ), + ).toEqual(['a']); + }); + + test('ignores locally declared Pick types', () => { + expect( + getPropNames( + `(props: Pick) => null; + type Pick = { local: string }; + interface Base { a: string }`, + ), + ).toEqual(['local']); + }); + + test('adds composes for an unresolved source in extends', () => { + expect( + getPropNames( + `(props: Props) => null; + import type { LinkProps } from 'next/link'; + interface Props extends Pick { a: string }`, + ), + ).toEqual(['a']); + expect(documentation.composes).toEqual(['LinkProps']); + }); + }); + test('does support utility types inline', () => { const definition = parse .statement( diff --git a/packages/react-docgen/src/utils/getTSPickOrOmit.ts b/packages/react-docgen/src/utils/getTSPickOrOmit.ts new file mode 100644 index 00000000000..a05f3ac141b --- /dev/null +++ b/packages/react-docgen/src/utils/getTSPickOrOmit.ts @@ -0,0 +1,78 @@ +import type { NodePath } from '@babel/traverse'; +import getTypeArguments from './getTypeArguments.js'; +import getTypeIdentifier from './getTypeIdentifier.js'; +import resolveToValue from './resolveToValue.js'; + +/** + * Returns the literal keys of a `Pick` or `Omit` key argument, such as `'a'` or + * `'a' | 'b'`. Returns null when any key is not a string or number literal. + */ +function getLiteralKeys(path: NodePath): Set | null { + if (path.isTSLiteralType()) { + const literal = path.get('literal'); + + if (literal.isStringLiteral() || literal.isNumericLiteral()) { + return new Set([`${literal.node.value}`]); + } + + return null; + } + + if (path.isTSUnionType()) { + const keys = new Set(); + + for (const typePath of path.get('types')) { + const typeKeys = getLiteralKeys(typePath); + + if (!typeKeys) return null; + typeKeys.forEach((key) => keys.add(key)); + } + + return keys; + } + + return null; +} + +/** + * Detects the builtin TypeScript `Pick` and `Omit` utility types + * when `K` is made of string or number literals. Types named `Pick` or `Omit` that are + * declared or imported locally are not matched. + */ +export default function getTSPickOrOmit( + path: NodePath, +): { name: 'Omit' | 'Pick'; source: NodePath; keys: Set } | null { + if ( + !path.isTSTypeReference() && + !['TSExpressionWithTypeArguments', 'TSInterfaceHeritage'].includes( + path.node.type, + ) + ) { + return null; + } + + const typeName = getTypeIdentifier(path); + + if (!typeName || !typeName.isIdentifier()) return null; + + const name = typeName.node.name; + + if ( + (name !== 'Pick' && name !== 'Omit') || + resolveToValue(typeName) !== typeName + ) { + return null; + } + + const typeArguments = getTypeArguments(path); + + if (!typeArguments.hasNode()) return null; + + const [source, keysPath] = typeArguments.get('params') as NodePath[]; + + if (!source || !keysPath) return null; + + const keys = getLiteralKeys(keysPath); + + return keys ? { name, source, keys } : null; +} diff --git a/packages/react-docgen/src/utils/getTypeFromReactComponent.ts b/packages/react-docgen/src/utils/getTypeFromReactComponent.ts index 5874488f9e9..5f3ff38e46a 100644 --- a/packages/react-docgen/src/utils/getTypeFromReactComponent.ts +++ b/packages/react-docgen/src/utils/getTypeFromReactComponent.ts @@ -27,6 +27,8 @@ import type { import getTypeIdentifier from './getTypeIdentifier.js'; import isReactBuiltinReference from './isReactBuiltinReference.js'; import unwrapBuiltinTSPropTypes from './unwrapBuiltinTSPropTypes.js'; +import getTSPickOrOmit from './getTSPickOrOmit.js'; +import getPropertyName from './getPropertyName.js'; function getStatelessPropsPath( componentDefinition: NodePath, @@ -196,15 +198,74 @@ export default (componentDefinition: NodePath): NodePath[] => { return typePaths.map((typePath) => unwrapBuiltinTSPropTypes(typePath)); }; +/** + * Returns the name of a TypeScript property or method signature, or null when + * the member has no static name. + */ +function getTSMemberName(path: NodePath): string | null { + if (!path.isTSPropertySignature() && !path.isTSMethodSignature()) { + return null; + } + + return getPropertyName(path); +} + +/** + * Binds the type arguments of a reference such as `Base` to the type + * parameters of the declaration it resolves to. + */ +function bindTypeArguments( + referencePath: NodePath, + resolvedPath: NodePath, + typeParams: TypeParameters | null, +): TypeParameters | null { + const typeArguments = getTypeArguments(referencePath); + const typeParameters = resolvedPath.get('typeParameters') as NodePath< + TSTypeParameterDeclaration | TypeParameterDeclaration | null | undefined + >; + + if (typeParameters.hasNode() && typeArguments.hasNode()) { + return getTypeParameters(typeParameters, typeArguments, typeParams); + } + + return typeParams; +} + export function applyToTypeProperties( documentation: Documentation, path: NodePath, callback: (propertyPath: NodePath, params: TypeParameters | null) => void, typeParams: TypeParameters | null, visited = new WeakSet(), + ancestors = new WeakSet(), ): void { - if (visited.has(path.node)) return; + if (visited.has(path.node) || ancestors.has(path.node)) return; visited.add(path.node); + ancestors.add(path.node); + + try { + applyToTypePropertiesOf( + documentation, + path, + callback, + typeParams, + visited, + ancestors, + ); + } finally { + ancestors.delete(path.node); + } +} + +function applyToTypePropertiesOf( + documentation: Documentation, + path: NodePath, + callback: (propertyPath: NodePath, params: TypeParameters | null) => void, + typeParams: TypeParameters | null, + visited: WeakSet, + ancestors: WeakSet, +): void { + const pickOrOmit = getTSPickOrOmit(path); if (path.isObjectTypeAnnotation()) { path @@ -215,14 +276,14 @@ export function applyToTypeProperties( .get('members') .forEach((propertyPath) => callback(propertyPath, typeParams)); } else if (path.isInterfaceDeclaration()) { - applyExtends(documentation, path, callback, typeParams, visited); + applyExtends(documentation, path, callback, typeParams, visited, ancestors); path .get('body') .get('properties') .forEach((propertyPath) => callback(propertyPath, typeParams)); } else if (path.isTSInterfaceDeclaration()) { - applyExtends(documentation, path, callback, typeParams, visited); + applyExtends(documentation, path, callback, typeParams, visited, ancestors); path .get('body') @@ -240,8 +301,35 @@ export function applyToTypeProperties( callback, typeParams, visited, + ancestors, ), ); + } else if (pickOrOmit) { + const { name, source, keys } = pickOrOmit; + const resolvedSource = source.isTSTypeReference() + ? resolveGenericTypeAnnotation(source) + : undefined; + + // The source gets a new visited set, so that a type that is also used + // elsewhere, as in `Pick & Omit`, is read again. Cycles + // still stop at the types on the current path. + applyToTypeProperties( + documentation, + resolvedSource ?? source, + (propertyPath, params) => { + const key = getTSMemberName(propertyPath); + const selected = key !== null && keys.has(key); + + if (name === 'Pick' ? selected : !selected) { + callback(propertyPath, params); + } + }, + resolvedSource?.isTSInterfaceDeclaration() + ? bindTypeArguments(source, resolvedSource, typeParams) + : typeParams, + new WeakSet(), + ancestors, + ); } else if (!path.isUnionTypeAnnotation()) { // The react-docgen output format does not currently allow // for the expression of union types @@ -254,6 +342,7 @@ export function applyToTypeProperties( callback, typeParams, visited, + ancestors, ); } } @@ -265,6 +354,7 @@ function applyExtends( callback: (propertyPath: NodePath, params: TypeParameters | null) => void, typeParams: TypeParameters | null, visited: WeakSet, + ancestors: WeakSet, ): void { const classExtends = path.get('extends'); @@ -276,6 +366,36 @@ function applyExtends( ( extendsPath: NodePath, ) => { + const pickOrOmit = getTSPickOrOmit(extendsPath); + + if (pickOrOmit) { + const { source } = pickOrOmit; + + if ( + source.isTSTypeReference() && + !resolveGenericTypeAnnotation(source) + ) { + // The picked type is not available, for example because it is + // imported from another package. + const idPath = getTypeIdentifier(source); + + if (idPath && idPath.isIdentifier()) { + documentation.addComposes(idPath.node.name); + } + } else { + applyToTypeProperties( + documentation, + extendsPath, + callback, + typeParams, + visited, + ancestors, + ); + } + + return; + } + const resolvedPath = resolveGenericTypeAnnotation(extendsPath); if (resolvedPath) { @@ -299,6 +419,7 @@ function applyExtends( callback, typeParams, visited, + ancestors, ); } else { const idPath = getTypeIdentifier(extendsPath); diff --git a/packages/react-docgen/src/utils/resolveGenericTypeAnnotation.ts b/packages/react-docgen/src/utils/resolveGenericTypeAnnotation.ts index 70b660079ae..09c4fdb6e76 100644 --- a/packages/react-docgen/src/utils/resolveGenericTypeAnnotation.ts +++ b/packages/react-docgen/src/utils/resolveGenericTypeAnnotation.ts @@ -3,12 +3,19 @@ import isUnreachableFlowType from '../utils/isUnreachableFlowType.js'; import resolveToValue from '../utils/resolveToValue.js'; import { unwrapUtilityType } from './flowUtilityTypes.js'; import getTypeIdentifier from './getTypeIdentifier.js'; +import getTSPickOrOmit from './getTSPickOrOmit.js'; function tryResolveGenericTypeAnnotation( path: NodePath, seen = new WeakSet(), ): NodePath | undefined { let typePath = unwrapUtilityType(path); + + // Keep `Pick` and `Omit` so that callers can select the keys. + if (getTSPickOrOmit(typePath)) { + return typePath; + } + const idPath = getTypeIdentifier(typePath); if (idPath) {