Skip to content

Commit e283081

Browse files
test(types): walk each type once, so a recursive alias ends
A type the walk reaches again, as an alias that holds an array of itself does through the array's element type, is skipped once it has been walked, under the first path that reached it.
1 parent 521dde0 commit e283081

1 file changed

Lines changed: 9 additions & 5 deletions

File tree

‎src/__tests__/types/optional-members.test.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -133,8 +133,6 @@ function optionalMembersRejectingUndefined(
133133
ts.isMethodDeclaration(declaration) ||
134134
typeNodeRejectsUndefined(declaration.type);
135135

136-
const checkedTypes = new Set<ts.Type>();
137-
138136
const referenceArguments = (type: ts.Type): readonly ts.Type[] =>
139137
(type.flags & ts.TypeFlags.Object) !== 0 &&
140138
((type as ts.ObjectType).objectFlags & ts.ObjectFlags.Reference) !== 0
@@ -194,8 +192,14 @@ function optionalMembersRejectingUndefined(
194192
}
195193
};
196194

195+
// A type is walked once, under the first path that reaches it, so a recursive one such as `type Nested = string | Nested[]` ends
196+
const walkedTypes = new Set<ts.Type>();
197+
197198
// An option type sits in a member's type itself, in a union or an intersection, in a tuple, in a generic's arguments, or behind a mapped type
198199
const descend = (type: ts.Type, path: string): void => {
200+
if (walkedTypes.has(type)) return;
201+
walkedTypes.add(type);
202+
199203
if (type.isUnionOrIntersection()) {
200204
for (const part of type.types) descend(part, path);
201205
} else if (
@@ -215,9 +219,6 @@ function optionalMembersRejectingUndefined(
215219

216220
// A resolved type's members as a consumer writes them, inherited, picked and mapped ones included, and the option types they reach
217221
const checkMembers = (type: ts.Type, path: string): void => {
218-
if (checkedTypes.has(type)) return;
219-
checkedTypes.add(type);
220-
221222
descendIntoStructure(type, path);
222223

223224
for (const property of checker.getPropertiesOfType(type)) {
@@ -530,6 +531,8 @@ export type GenericNamed<T> = [first: T, second?: number];
530531
export interface Wrapper<T> { box?: { inner?: string; value?: T | undefined } | undefined }
531532
export interface FirstUse { wrapper?: Wrapper<string> | undefined }
532533
export interface SecondUse { wrapper?: Wrapper<number> | undefined }
534+
type Nested = string | Item | Nested[];
535+
export interface RecursiveOptions { nested?: Nested | undefined }
533536
`;
534537

535538
let program: ts.Program;
@@ -604,6 +607,7 @@ test.each([
604607
],
605608
["GenericPair", ["87: number?"]],
606609
["GenericNamed", ["88: second?: number"]],
610+
["RecursiveOptions", ["Item.tag"]],
607611
])(
608612
"the walk reaches the options %s holds, and names each under the type that declares it",
609613
(name, expected) => {

0 commit comments

Comments
 (0)