Skip to content

Commit

Permalink
fix(type-utils): isTypeReadonly now handles conditional types (#4421)
Browse files Browse the repository at this point in the history
  • Loading branch information
RebeccaStevens committed Jan 17, 2022
1 parent f4016c2 commit 39a6806
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
15 changes: 15 additions & 0 deletions packages/type-utils/src/isTypeReadonly.ts
@@ -1,5 +1,6 @@
import { ESLintUtils } from '@typescript-eslint/utils';
import {
isConditionalType,
isObjectType,
isUnionType,
isUnionOrIntersectionType,
Expand Down Expand Up @@ -223,6 +224,20 @@ function isTypeReadonlyRecurser(
return readonlyness;
}

if (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 (!isObjectType(type) && !isUnionOrIntersectionType(type)) {
Expand Down
32 changes: 32 additions & 0 deletions packages/type-utils/tests/isTypeReadonly.test.ts
Expand Up @@ -164,6 +164,38 @@ describe('isTypeReadonly', () => {
])('handles a union of non fully readonly types', runTests);
});
});

describe('Conditional Types', () => {
describe('is readonly', () => {
const runTests = runTestIsReadonly;

it.each([
[
'type Test<T> = T extends readonly number[] ? readonly string[] : readonly number[];',
],
])('handles conditional type that are fully readonly', runTests);

it.each([
[
'type Test<T> = T extends number[] ? readonly string[] : readonly number[];',
],
])('should ignore mutable conditions', runTests);
});

describe('is not readonly', () => {
const runTests = runTestIsNotReadonly;

it.each([
['type Test<T> = T extends number[] ? string[] : number[];'],
[
'type Test<T> = T extends number[] ? string[] : readonly number[];',
],
[
'type Test<T> = T extends number[] ? readonly string[] : number[];',
],
])('handles non fully readonly conditional types', runTests);
});
});
});

describe('treatMethodsAsReadonly', () => {
Expand Down

0 comments on commit 39a6806

Please sign in to comment.