-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
isTypeReadonly.ts
326 lines (283 loc) · 8.6 KB
/
isTypeReadonly.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
import { ESLintUtils } from '@typescript-eslint/utils';
import * as tools from 'ts-api-utils';
import * as ts from 'typescript';
import { getTypeOfPropertyOfType } from './propertyTypes';
const enum Readonlyness {
/** the type cannot be handled by the function */
UnknownType = 1,
/** the type is mutable */
Mutable = 2,
/** the type is readonly */
Readonly = 3,
}
export interface ReadonlynessOptions {
readonly treatMethodsAsReadonly?: boolean;
}
export const readonlynessOptionsSchema = {
type: 'object',
additionalProperties: false,
properties: {
treatMethodsAsReadonly: {
type: 'boolean',
},
},
};
export const readonlynessOptionsDefaults: ReadonlynessOptions = {
treatMethodsAsReadonly: false,
};
function hasSymbol(node: ts.Node): node is ts.Node & { symbol: ts.Symbol } {
return Object.prototype.hasOwnProperty.call(node, 'symbol');
}
function isTypeReadonlyArrayOrTuple(
checker: ts.TypeChecker,
type: ts.Type,
options: ReadonlynessOptions,
seenTypes: Set<ts.Type>,
): Readonlyness {
function checkTypeArguments(arrayType: ts.TypeReference): Readonlyness {
const typeArguments =
// getTypeArguments was only added in TS3.7
checker.getTypeArguments
? checker.getTypeArguments(arrayType)
: arrayType.typeArguments ?? [];
// this shouldn't happen in reality as:
// - tuples require at least 1 type argument
// - ReadonlyArray requires at least 1 type argument
/* istanbul ignore if */ if (typeArguments.length === 0) {
return Readonlyness.Readonly;
}
// validate the element types are also readonly
if (
typeArguments.some(
typeArg =>
isTypeReadonlyRecurser(checker, typeArg, options, seenTypes) ===
Readonlyness.Mutable,
)
) {
return Readonlyness.Mutable;
}
return Readonlyness.Readonly;
}
if (checker.isArrayType(type)) {
const symbol = ESLintUtils.nullThrows(
type.getSymbol(),
ESLintUtils.NullThrowsReasons.MissingToken('symbol', 'array type'),
);
const escapedName = symbol.getEscapedName();
if (escapedName === 'Array') {
return Readonlyness.Mutable;
}
return checkTypeArguments(type);
}
if (checker.isTupleType(type)) {
if (!type.target.readonly) {
return Readonlyness.Mutable;
}
return checkTypeArguments(type);
}
return Readonlyness.UnknownType;
}
function isTypeReadonlyObject(
checker: ts.TypeChecker,
type: ts.Type,
options: ReadonlynessOptions,
seenTypes: Set<ts.Type>,
): Readonlyness {
function checkIndexSignature(kind: ts.IndexKind): Readonlyness {
const indexInfo = checker.getIndexInfoOfType(type, kind);
if (indexInfo) {
if (!indexInfo.isReadonly) {
return Readonlyness.Mutable;
}
if (indexInfo.type === type || seenTypes.has(indexInfo.type)) {
return Readonlyness.Readonly;
}
return isTypeReadonlyRecurser(
checker,
indexInfo.type,
options,
seenTypes,
);
}
return Readonlyness.UnknownType;
}
const properties = type.getProperties();
if (properties.length) {
// ensure the properties are marked as readonly
for (const property of properties) {
if (options.treatMethodsAsReadonly) {
if (
property.valueDeclaration !== undefined &&
hasSymbol(property.valueDeclaration) &&
tools.isSymbolFlagSet(
property.valueDeclaration.symbol,
ts.SymbolFlags.Method,
)
) {
continue;
}
const declarations = property.getDeclarations();
const lastDeclaration =
declarations !== undefined && declarations.length > 0
? declarations[declarations.length - 1]
: undefined;
if (
lastDeclaration !== undefined &&
hasSymbol(lastDeclaration) &&
tools.isSymbolFlagSet(lastDeclaration.symbol, ts.SymbolFlags.Method)
) {
continue;
}
}
if (
tools.isPropertyReadonlyInType(type, property.getEscapedName(), checker)
) {
continue;
}
const name = ts.getNameOfDeclaration(property.valueDeclaration);
if (name && ts.isPrivateIdentifier(name)) {
continue;
}
return Readonlyness.Mutable;
}
// all properties were readonly
// now ensure that all of the values are readonly also.
// do this after checking property readonly-ness as a perf optimization,
// as we might be able to bail out early due to a mutable property before
// doing this deep, potentially expensive check.
for (const property of properties) {
const propertyType = ESLintUtils.nullThrows(
getTypeOfPropertyOfType(checker, type, property),
ESLintUtils.NullThrowsReasons.MissingToken(
`property "${property.name}"`,
'type',
),
);
// handle recursive types.
// we only need this simple check, because a mutable recursive type will break via the above prop readonly check
if (seenTypes.has(propertyType)) {
continue;
}
if (
isTypeReadonlyRecurser(checker, propertyType, options, seenTypes) ===
Readonlyness.Mutable
) {
return Readonlyness.Mutable;
}
}
}
const isStringIndexSigReadonly = checkIndexSignature(ts.IndexKind.String);
if (isStringIndexSigReadonly === Readonlyness.Mutable) {
return isStringIndexSigReadonly;
}
const isNumberIndexSigReadonly = checkIndexSignature(ts.IndexKind.Number);
if (isNumberIndexSigReadonly === Readonlyness.Mutable) {
return isNumberIndexSigReadonly;
}
return Readonlyness.Readonly;
}
// a helper function to ensure the seenTypes map is always passed down, except by the external caller
function isTypeReadonlyRecurser(
checker: ts.TypeChecker,
type: ts.Type,
options: ReadonlynessOptions,
seenTypes: Set<ts.Type>,
): Readonlyness.Readonly | Readonlyness.Mutable {
seenTypes.add(type);
if (tools.isUnionType(type)) {
// all types in the union must be readonly
const result = tools
.unionTypeParts(type)
.every(
t =>
seenTypes.has(t) ||
isTypeReadonlyRecurser(checker, t, options, seenTypes) ===
Readonlyness.Readonly,
);
const readonlyness = result ? Readonlyness.Readonly : Readonlyness.Mutable;
return readonlyness;
}
if (tools.isIntersectionType(type)) {
// Special case for handling arrays/tuples (as readonly arrays/tuples always have mutable methods).
if (
type.types.some(t => checker.isArrayType(t) || checker.isTupleType(t))
) {
const allReadonlyParts = type.types.every(
t =>
seenTypes.has(t) ||
isTypeReadonlyRecurser(checker, t, options, seenTypes) ===
Readonlyness.Readonly,
);
return allReadonlyParts ? Readonlyness.Readonly : Readonlyness.Mutable;
}
// Normal case.
const isReadonlyObject = isTypeReadonlyObject(
checker,
type,
options,
seenTypes,
);
if (isReadonlyObject !== Readonlyness.UnknownType) {
return isReadonlyObject;
}
}
if (tools.isConditionalType(type)) {
const result = [type.root.node.trueType, type.root.node.falseType]
.map(checker.getTypeFromTypeNode)
.every(
t =>
seenTypes.has(t) ||
isTypeReadonlyRecurser(checker, t, options, seenTypes) ===
Readonlyness.Readonly,
);
const readonlyness = result ? Readonlyness.Readonly : Readonlyness.Mutable;
return readonlyness;
}
// all non-object, non-intersection types are readonly.
// this should only be primitive types
if (!tools.isObjectType(type)) {
return Readonlyness.Readonly;
}
// pure function types are readonly
if (
type.getCallSignatures().length > 0 &&
type.getProperties().length === 0
) {
return Readonlyness.Readonly;
}
const isReadonlyArray = isTypeReadonlyArrayOrTuple(
checker,
type,
options,
seenTypes,
);
if (isReadonlyArray !== Readonlyness.UnknownType) {
return isReadonlyArray;
}
const isReadonlyObject = isTypeReadonlyObject(
checker,
type,
options,
seenTypes,
);
/* istanbul ignore else */ if (
isReadonlyObject !== Readonlyness.UnknownType
) {
return isReadonlyObject;
}
throw new Error('Unhandled type');
}
/**
* Checks if the given type is readonly
*/
function isTypeReadonly(
checker: ts.TypeChecker,
type: ts.Type,
options: ReadonlynessOptions = readonlynessOptionsDefaults,
): boolean {
return (
isTypeReadonlyRecurser(checker, type, options, new Set()) ===
Readonlyness.Readonly
);
}
export { isTypeReadonly };