forked from typescript-eslint/typescript-eslint
/
types.ts
292 lines (257 loc) · 6.96 KB
/
types.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import {
isTypeReference,
isUnionOrIntersectionType,
unionTypeParts,
} from 'tsutils';
import * as ts from 'typescript';
/**
* @param type Type being checked by name.
* @param allowedNames Symbol names checking on the type.
* @returns Whether the type is, extends, or contains all of the allowed names.
*/
export function containsAllTypesByName(
type: ts.Type,
allowAny: boolean,
allowedNames: Set<string>,
): boolean {
if (isTypeFlagSet(type, ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {
return !allowAny;
}
if (isTypeReference(type)) {
type = type.target;
}
if (
typeof type.symbol !== 'undefined' &&
allowedNames.has(type.symbol.name)
) {
return true;
}
if (isUnionOrIntersectionType(type)) {
return type.types.every(t =>
containsAllTypesByName(t, allowAny, allowedNames),
);
}
const bases = type.getBaseTypes();
return (
typeof bases !== 'undefined' &&
bases.length > 0 &&
bases.every(t => containsAllTypesByName(t, allowAny, allowedNames))
);
}
/**
* Get the type name of a given type.
* @param typeChecker The context sensitive TypeScript TypeChecker.
* @param type The type to get the name of.
*/
export function getTypeName(
typeChecker: ts.TypeChecker,
type: ts.Type,
): string {
// It handles `string` and string literal types as string.
if ((type.flags & ts.TypeFlags.StringLike) !== 0) {
return 'string';
}
// If the type is a type parameter which extends primitive string types,
// but it was not recognized as a string like. So check the constraint
// type of the type parameter.
if ((type.flags & ts.TypeFlags.TypeParameter) !== 0) {
// `type.getConstraint()` method doesn't return the constraint type of
// the type parameter for some reason. So this gets the constraint type
// via AST.
const node = type.symbol.declarations[0] as ts.TypeParameterDeclaration;
if (node.constraint != null) {
return getTypeName(
typeChecker,
typeChecker.getTypeFromTypeNode(node.constraint),
);
}
}
// If the type is a union and all types in the union are string like,
// return `string`. For example:
// - `"a" | "b"` is string.
// - `string | string[]` is not string.
if (
type.isUnion() &&
type.types
.map(value => getTypeName(typeChecker, value))
.every(t => t === 'string')
) {
return 'string';
}
// If the type is an intersection and a type in the intersection is string
// like, return `string`. For example: `string & {__htmlEscaped: void}`
if (
type.isIntersection() &&
type.types
.map(value => getTypeName(typeChecker, value))
.some(t => t === 'string')
) {
return 'string';
}
return typeChecker.typeToString(type);
}
/**
* Resolves the given node's type. Will resolve to the type's generic constraint, if it has one.
*/
export function getConstrainedTypeAtLocation(
checker: ts.TypeChecker,
node: ts.Node,
): ts.Type {
const nodeType = checker.getTypeAtLocation(node);
const constrained = checker.getBaseConstraintOfType(nodeType);
return constrained ?? nodeType;
}
/**
* Checks if the given type is (or accepts) nullable
* @param isReceiver true if the type is a receiving type (i.e. the type of a called function's parameter)
*/
export function isNullableType(
type: ts.Type,
{
isReceiver = false,
allowUndefined = true,
}: { isReceiver?: boolean; allowUndefined?: boolean } = {},
): boolean {
const flags = getTypeFlags(type);
if (isReceiver && flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {
return true;
}
if (allowUndefined) {
return (flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)) !== 0;
} else {
return (flags & ts.TypeFlags.Null) !== 0;
}
}
/**
* Gets the declaration for the given variable
*/
export function getDeclaration(
checker: ts.TypeChecker,
node: ts.Expression,
): ts.Declaration | null {
const symbol = checker.getSymbolAtLocation(node);
if (!symbol) {
return null;
}
const declarations = symbol.declarations;
if (!declarations) {
return null;
}
return declarations[0];
}
/**
* Gets all of the type flags in a type, iterating through unions automatically
*/
export function getTypeFlags(type: ts.Type): ts.TypeFlags {
let flags: ts.TypeFlags = 0;
for (const t of unionTypeParts(type)) {
flags |= t.flags;
}
return flags;
}
/**
* Checks if the given type is (or accepts) the given flags
* @param isReceiver true if the type is a receiving type (i.e. the type of a called function's parameter)
*/
export function isTypeFlagSet(
type: ts.Type,
flagsToCheck: ts.TypeFlags,
isReceiver?: boolean,
): boolean {
const flags = getTypeFlags(type);
if (isReceiver && flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {
return true;
}
return (flags & flagsToCheck) !== 0;
}
/**
* @returns Whether a type is an instance of the parent type, including for the parent's base types.
*/
export function typeIsOrHasBaseType(
type: ts.Type,
parentType: ts.Type,
): boolean {
if (type.symbol === undefined || parentType.symbol === undefined) {
return false;
}
const typeAndBaseTypes = [type];
const ancestorTypes = type.getBaseTypes();
if (ancestorTypes !== undefined) {
typeAndBaseTypes.push(...ancestorTypes);
}
for (const baseType of typeAndBaseTypes) {
if (
baseType.symbol !== undefined &&
baseType.symbol.name === parentType.symbol.name
) {
return true;
}
}
return false;
}
/**
* Gets the source file for a given node
*/
export function getSourceFileOfNode(node: ts.Node): ts.SourceFile {
while (node && node.kind !== ts.SyntaxKind.SourceFile) {
node = node.parent;
}
return node as ts.SourceFile;
}
export function getTokenAtPosition(
sourceFile: ts.SourceFile,
position: number,
): ts.Node {
const queue: ts.Node[] = [sourceFile];
let current: ts.Node;
while (queue.length > 0) {
current = queue.shift()!;
// find the child that contains 'position'
for (const child of current.getChildren(sourceFile)) {
const start = child.getFullStart();
if (start > position) {
// If this child begins after position, then all subsequent children will as well.
return current;
}
const end = child.getEnd();
if (
position < end ||
(position === end && child.kind === ts.SyntaxKind.EndOfFileToken)
) {
queue.push(child);
break;
}
}
}
return current!;
}
export interface EqualsKind {
isPositive: boolean;
isStrict: boolean;
}
export function getEqualsKind(operator: string): EqualsKind | undefined {
switch (operator) {
case '==':
return {
isPositive: true,
isStrict: false,
};
case '===':
return {
isPositive: true,
isStrict: true,
};
case '!=':
return {
isPositive: false,
isStrict: false,
};
case '!==':
return {
isPositive: true,
isStrict: true,
};
default:
return undefined;
}
}