Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/ts-pick-omit-props.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'react-docgen': minor
---

Extract props from the TypeScript `Pick<T, K>` and `Omit<T, K>` utility types
when the keys are string or number literals, including in type aliases,
intersections and interface `extends`.
139 changes: 139 additions & 0 deletions packages/react-docgen/src/handlers/__tests__/codeTypeHandler-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ArrowFunctionExpression>;

codeTypeHandler(documentation, definition);

return Object.keys(documentation.descriptors);
}

test('picks props', () => {
expect(
getPropNames(
`(props: Pick<Props, 'a' | 'b'>) => null;
interface Props { a: string; b: number; c: boolean }`,
),
).toEqual(['a', 'b']);
});

test('omits props', () => {
expect(
getPropNames(
`(props: Omit<Props, 'b'>) => null;
interface Props { a: string; b: number; c: boolean }`,
),
).toEqual(['a', 'c']);
});

test('reads the docs of picked props', () => {
getPropNames(
`(props: Pick<Props, 'a'>) => 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<Base, 'c'> & { 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<Base, 'a'> { c: boolean }`,
),
).toEqual(['a', 'c']);
expect(documentation.composes).toEqual([]);
});

test('supports nested Pick and Omit', () => {
expect(
getPropNames(
`(props: Omit<Pick<Base, 'a' | 'b'>, '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<Base, 'a'> & Omit<Base, 'a'>) => 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, 'a'> { a: string; b: number }`,
),
).toEqual(['a', 'b']);
});

test('binds type arguments of the picked type', () => {
getPropNames(
`(props: Props) => null;
interface Base<T> { value: T; other: number }
interface Props extends Pick<Base<string>, 'value'> {}`,
);

expect(documentation.descriptors).toEqual({
value: { required: true, tsType: { name: 'string' }, description: '' },
});
});

test('supports number keys', () => {
expect(
getPropNames(
`(props: Omit<Props, 0>) => null;
interface Props { 0: string; a: number }`,
),
).toEqual(['a']);
});

test('ignores locally declared Pick types', () => {
expect(
getPropNames(
`(props: Pick<Base, 'a'>) => null;
type Pick<T, K> = { 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<LinkProps, 'href'> { a: string }`,
),
).toEqual(['a']);
expect(documentation.composes).toEqual(['LinkProps']);
});
});

test('does support utility types inline', () => {
const definition = parse
.statement(
Expand Down
78 changes: 78 additions & 0 deletions packages/react-docgen/src/utils/getTSPickOrOmit.ts
Original file line number Diff line number Diff line change
@@ -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<string> | 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<string>();

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<T, K>` and `Omit<T, K>` 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<string> } | 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;
}
Loading