Skip to content

Commit 042f3a5

Browse files
authored
Handle type predicates in api check. (#2201)
1 parent f2314b8 commit 042f3a5

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

scripts/components/api-changes-validator/api_usage_statements_generators.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -566,7 +566,18 @@ export class CallableUsageStatementsGenerator
566566
).generate().usageStatement ?? '';
567567
let returnValueAssignmentTarget = '';
568568
if (this.functionType.type.kind !== ts.SyntaxKind.VoidKeyword) {
569-
returnValueAssignmentTarget = `const returnValue: ${this.functionType.type.getText()} = `;
569+
let returnType;
570+
if (this.functionType.type.kind === ts.SyntaxKind.TypePredicate) {
571+
// Example type predicate looks like this
572+
// '(input: unknown) => input is SampleType;'
573+
// It's a special syntax that tells compiler that it's safe to assume
574+
// type after invoking the check.
575+
// But when it comes to value assignment this is treated as boolean.
576+
returnType = 'boolean';
577+
} else {
578+
returnType = this.functionType.type.getText();
579+
}
580+
returnValueAssignmentTarget = `const returnValue: ${returnType} = `;
570581
}
571582
const minParameterUsage =
572583
new CallableParameterUsageStatementsGenerator(

scripts/components/api-changes-validator/test-resources/test-projects/without-breaks/project-without-breaks/API.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,4 +84,10 @@ export type SampleTypeThatReferencesFunction<T extends typeof someFunction1> = {
8484
export type SampleIgnoredType = {
8585
someProperty: string;
8686
};
87+
88+
export const sampleTypePredicate: (input: unknown) => input is SampleType;
89+
90+
export class SampleClassWithTypePredicate {
91+
static sampleTypePredicate: (input: unknown) => input is SampleType;
92+
}
8793
```

scripts/components/api-changes-validator/test-resources/test-projects/without-breaks/project-without-breaks/src/index.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,3 +115,13 @@ export type SampleTypeThatReferencesFunction<T extends typeof someFunction1> = {
115115
export type SampleIgnoredType = {
116116
someProperty: number;
117117
};
118+
119+
export const sampleTypePredicate = (input: unknown): input is SampleType => {
120+
throw new Error();
121+
};
122+
123+
export class SampleClassWithTypePredicate {
124+
static sampleTypePredicate = (input: unknown): input is SampleType => {
125+
throw new Error();
126+
};
127+
}

0 commit comments

Comments
 (0)