Skip to content

fix(type-utils): isTypeReadonly now handles conditional types #4421

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
merged 16 commits into from
Jan 17, 2022
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
15 changes: 15 additions & 0 deletions packages/type-utils/src/isTypeReadonly.ts
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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