|
1 | 1 | import ts from "typescript"; |
2 | | -import { describe, expect, it } from "vitest"; |
| 2 | +import { describe, expect, expectTypeOf, it } from "vitest"; |
3 | 3 |
|
4 | 4 | import { createSourceFileAndTypeChecker } from "../../test/utils"; |
5 | 5 | import { |
6 | 6 | isConditionalType, |
7 | 7 | isEnumType, |
8 | 8 | isIntersectionType, |
9 | 9 | isObjectType, |
| 10 | + isTypeParameter, |
10 | 11 | isUnionOrIntersectionType, |
11 | 12 | isUnionType, |
12 | 13 | isUniqueESSymbolType, |
@@ -74,6 +75,45 @@ describe("isObjectType", () => { |
74 | 75 | }); |
75 | 76 | }); |
76 | 77 |
|
| 78 | +describe("isTypeParameter", () => { |
| 79 | + it("should return true for a type parameter", () => { |
| 80 | + const sourceText = `type Test<TParam> = { foo: string };`; |
| 81 | + const { sourceFile, typeChecker } = |
| 82 | + createSourceFileAndTypeChecker(sourceText); |
| 83 | + |
| 84 | + const testNode = sourceFile.statements.at(-1) as ts.TypeAliasDeclaration; |
| 85 | + const tParamNode = testNode.typeParameters?.[0]; |
| 86 | + expect(tParamNode).toBeDefined(); |
| 87 | + |
| 88 | + const tParamType = typeChecker.getTypeAtLocation(tParamNode!); |
| 89 | + |
| 90 | + const isTParamATypeParameter = isTypeParameter(tParamType); |
| 91 | + // type test - see https://github.com/JoshuaKGoldberg/ts-api-utils/issues/382 |
| 92 | + if (isTParamATypeParameter) { |
| 93 | + expectTypeOf(tParamType).toEqualTypeOf<ts.TypeParameter>(); |
| 94 | + } else { |
| 95 | + expectTypeOf(tParamType).toEqualTypeOf<ts.Type>(); |
| 96 | + } |
| 97 | + |
| 98 | + expect(isTParamATypeParameter).toBe(true); |
| 99 | + }); |
| 100 | + |
| 101 | + it("should return false when not a type parameter", () => { |
| 102 | + const sourceText = `type Test<T> = { foo: string };`; |
| 103 | + const testType = getTypeForTypeNode(sourceText); |
| 104 | + |
| 105 | + const isTestATypeParameter = isTypeParameter(testType); |
| 106 | + // type test - see https://github.com/JoshuaKGoldberg/ts-api-utils/issues/382 |
| 107 | + if (isTestATypeParameter) { |
| 108 | + expectTypeOf(testType).toEqualTypeOf<ts.TypeParameter>(); |
| 109 | + } else { |
| 110 | + expectTypeOf(testType).toEqualTypeOf<ts.Type>(); |
| 111 | + } |
| 112 | + |
| 113 | + expect(isTestATypeParameter).toBe(false); |
| 114 | + }); |
| 115 | +}); |
| 116 | + |
77 | 117 | describe("isUnionOrIntersectionType", () => { |
78 | 118 | it.each([ |
79 | 119 | [false, "type Test = 1;"], |
|
0 commit comments