Skip to content
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

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

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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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;
}
bradzacher marked this conversation as resolved.
Show resolved Hide resolved

// 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