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
6 changes: 6 additions & 0 deletions .changeset/readonly-ts-arrays.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'react-docgen': patch
---

Read the type wrapped by a TypeScript `readonly` operator, so
`readonly string[]` and `readonly [string, number]` are no longer `unknown`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
interface Props {
names: readonly string[];
pair: readonly [string, number];
values: readonly (string | number)[];
}

export const MyComponent = ({ names, pair, values }: Props) => <div />;
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
[
{
"description": "",
"displayName": "MyComponent",
"methods": [],
"props": {
"names": {
"required": true,
"tsType": {
"name": "Array",
"elements": [
{
"name": "string"
}
],
"raw": "readonly string[]"
},
"description": ""
},
"pair": {
"required": true,
"tsType": {
"name": "tuple",
"raw": "readonly [string, number]",
"elements": [
{
"name": "string"
},
{
"name": "number"
}
]
},
"description": ""
},
"values": {
"required": true,
"tsType": {
"name": "Array",
"elements": [
{
"name": "union",
"raw": "string | number",
"elements": [
{
"name": "string"
},
{
"name": "number"
}
]
}
],
"raw": "readonly (string | number)[]"
},
"description": ""
}
}
}
]
9 changes: 9 additions & 0 deletions packages/react-docgen/src/utils/getTSType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,15 @@ function handleTSTypeOperator(
path: NodePath<TSTypeOperator>,
typeParams: TypeParameters | null,
): TypeDescriptor<TSFunctionSignatureType> | null {
if (path.node.operator === 'readonly') {
// `readonly string[]` and `readonly [A, B]` describe the same values as the
// array or tuple they wrap.
return {
...getTSTypeWithResolvedTypes(path.get('typeAnnotation'), typeParams),
raw: printValue(path),
};
}

if (path.node.operator !== 'keyof') {
return null;
}
Expand Down
6 changes: 6 additions & 0 deletions packages/typescript/src/utils/getTSType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,12 @@ export default function getTSType(
if (node.type === 'TSTypeOperator') {
const annotation = child(node, 'typeAnnotation');

if (node.operator === 'readonly' && annotation) {
const type = getTSType(file, annotation, resolving);

if (type) return { ...type, raw: source(file, node) };
}

if (node.operator === 'keyof' && annotation?.type === 'TSTypeLiteral') {
return {
name: 'union',
Expand Down