Skip to content

feat(type-utils): support intersection types in TypeOrValueSpecifier #9633

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
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
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
import * as tsutils from 'ts-api-utils';
import type * as ts from 'typescript';

export function specifierNameMatches(
type: ts.Type,
name: string[] | string,
names: string[] | string,
): boolean {
if (typeof name === 'string') {
name = [name];
if (typeof names === 'string') {
names = [names];
}
if (name.some(item => item === type.intrinsicName)) {

const symbol = type.aliasSymbol ?? type.getSymbol();
const candidateNames = symbol
? [symbol.escapedName as string, type.intrinsicName]
: [type.intrinsicName];

if (names.some(item => candidateNames.includes(item))) {
return true;
}
const symbol = type.aliasSymbol ?? type.getSymbol();
if (symbol === undefined) {
return false;

if (tsutils.isIntersectionType(type)) {
return type.types.some(subType => specifierNameMatches(subType, names));
}
return name.some(item => (item as ts.__String) === symbol.escapedName);

return false;
}
36 changes: 36 additions & 0 deletions packages/type-utils/tests/TypeOrValueSpecifier.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,42 @@ describe('TypeOrValueSpecifier', () => {
],
])('matches a matching package specifier: %s', runTestPositive);

it.each<[string, TypeOrValueSpecifier]>([
[
`
type Other = { __otherBrand: true };
type SafePromise = Promise<number> & { __safeBrand: string };
type JoinedPromise = SafePromise & {};
`,
{ from: 'file', name: ['Other'] },
],
// The SafePromise alias acts as an actual alias ("cut-and-paste"). I.e.:
// type JoinedPromise = Promise<number> & { __safeBrand: string };
[
`
type SafePromise = Promise<number> & { __safeBrand: string };
type JoinedPromise = SafePromise & {};
`,
{ from: 'file', name: ['SafePromise'] },
],
])(
"doesn't match a mismatched type specifier for an intersection type: %s",
runTestNegative,
);

it.each<[string, TypeOrValueSpecifier]>([
[
`
type SafePromise = Promise<number> & { __safeBrand: string };
type JoinedPromise = SafePromise & {};
`,
{ from: 'file', name: ['JoinedPromise'] },
],
])(
'matches a matching type specifier for an intersection type: %s',
runTestPositive,
);

it("does not match a `declare global` with the 'global' package name", () => {
runTestNegative(
`
Expand Down
Loading