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

Handle 'keyof' for generic tuple types #39218

Merged
merged 6 commits into from
Jun 25, 2020
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
56 changes: 33 additions & 23 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10195,7 +10195,8 @@ namespace ts {
return type;
}
if (type.flags & TypeFlags.Index) {
return getIndexType(getApparentType((<IndexType>type).type));
const t = getApparentType((<IndexType>type).type);
return isGenericTupleType(t) ? getKnownKeysOfTupleType(t) : getIndexType(t);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about the keyof T in {[K in keyof T]: any} where T extends [...Some, ...Variadic, ...Tuple]? That will fall back to getIndexType (since T isn't a tuple type), which seems to still be lacking a specialized implementation for variadic tuples? Or is the getLiteralTypeFromProperties fallback sufficient? If so, why would we need to call out isTupleType here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The apparent type of a tuple type is simply the tuple type itself, so we need a special case for (generic) tuple types here as we'd otherwise just create the same type again. I'm not quite sure what you're asking about the mapped type. It's homomorphic, which means we'll just iterate over getPropertiesOfType for T, which works just fine for a type parameter constrained to a generic tuple type.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, but what if we have a non-homomorphic keyof T? (Eg, because it appears via instantiation). The apparent type of the tuple being itself is fine, so long as getIndexType handles it. If it does, then this is redundant. If it does not, then this doesn't handle the case where the apparent type resolves to a tuple type.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, seems better to do the check after getApparentType. Although it is surprisingly hard to construct an example where this fails because we typically call getApparentType on a mapped type before resolving members and that turns a MappedType<keyof T> into MappedType<keyof [...Some, ...Variadic]> before we even get to this code. But anyways, I'll make the change.

}
if (type.flags & TypeFlags.Conditional) {
if ((<ConditionalType>type).root.isDistributive) {
Expand Down Expand Up @@ -10520,9 +10521,6 @@ namespace ts {
return indexedAccess;
}
}
if (isGenericTupleType(type.objectType)) {
return getIndexTypeOfType(type.objectType, IndexKind.Number);
}
const objectConstraint = getSimplifiedTypeOrConstraint(type.objectType);
if (objectConstraint && objectConstraint !== type.objectType) {
return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType);
Expand Down Expand Up @@ -10711,9 +10709,6 @@ namespace ts {
return keyofConstraintType;
}
if (t.flags & TypeFlags.IndexedAccess) {
if (isGenericTupleType((<IndexedAccessType>t).objectType)) {
return getIndexTypeOfType((<IndexedAccessType>t).objectType, IndexKind.Number);
}
const baseObjectType = getBaseConstraint((<IndexedAccessType>t).objectType);
const baseIndexType = getBaseConstraint((<IndexedAccessType>t).indexType);
const baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType);
Expand Down Expand Up @@ -12647,6 +12642,11 @@ namespace ts {
/*readonly*/ false, target.labeledElementDeclarations && target.labeledElementDeclarations.slice(index, endIndex));
}

function getKnownKeysOfTupleType(type: TupleTypeReference) {
return getUnionType(append(arrayOf(type.target.fixedLength, i => getLiteralType("" + i)),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the tuple has a rest, shouldn't the keys contain number?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The keys already contain number because all array types have an index signature.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm. I question if we should be OK with 2 being assignable to keyof [...T] where T extends [] | [object]. But... I guess it's inline with how we already handle the keys of tuples?

getIndexType(type.target.readonly ? globalReadonlyArrayType : globalArrayType)));
}

function getTypeFromOptionalTypeNode(node: OptionalTypeNode): Type {
const type = getTypeFromTypeNode(node.type);
return strictNullChecks ? getOptionalType(type) : type;
Expand Down Expand Up @@ -16831,11 +16831,11 @@ namespace ts {
}
}

// For a generic type T, [...T] is assignable to T, T is assignable to readonly [...T], and T is assignable
// to [...T] when T is constrained to a mutable array or tuple type.
if (isSingleElementGenericTupleType(source) && getTypeArguments(source)[0] === target && !source.target.readonly ||
isSingleElementGenericTupleType(target) && getTypeArguments(target)[0] === source && (target.target.readonly || isMutableArrayOrTuple(getBaseConstraintOfType(source) || source))) {
return Ternary.True;
// For a generic type T and a type U that is assignable to T, [...U] is assignable to T, U is assignable to readonly [...T],
// and U is assignable to [...T] when U is constrained to a mutable array or tuple type.
if (isSingleElementGenericTupleType(source) && !source.target.readonly && (result = isRelatedTo(getTypeArguments(source)[0], target)) ||
isSingleElementGenericTupleType(target) && (target.target.readonly || isMutableArrayOrTuple(getBaseConstraintOfType(source) || source)) && (result = isRelatedTo(source, getTypeArguments(target)[0]))) {
return result;
}

if (target.flags & TypeFlags.TypeParameter) {
Expand All @@ -16851,22 +16851,32 @@ namespace ts {
}
}
else if (target.flags & TypeFlags.Index) {
const targetType = (target as IndexType).type;
// A keyof S is related to a keyof T if T is related to S.
if (source.flags & TypeFlags.Index) {
if (result = isRelatedTo((<IndexType>target).type, (<IndexType>source).type, /*reportErrors*/ false)) {
if (result = isRelatedTo(targetType, (<IndexType>source).type, /*reportErrors*/ false)) {
return result;
}
}
// A type S is assignable to keyof T if S is assignable to keyof C, where C is the
// simplified form of T or, if T doesn't simplify, the constraint of T.
const constraint = getSimplifiedTypeOrConstraint((<IndexType>target).type);
if (constraint) {
// We require Ternary.True here such that circular constraints don't cause
// false positives. For example, given 'T extends { [K in keyof T]: string }',
// 'keyof T' has itself as its constraint and produces a Ternary.Maybe when
// related to other types.
if (isRelatedTo(source, getIndexType(constraint, (target as IndexType).stringsOnly), reportErrors) === Ternary.True) {
return Ternary.True;
if (isTupleType(targetType)) {
// An index type can have a tuple type target when the tuple type contains variadic elements.
// Check if the source is related to the known keys of the tuple type.
if (result = isRelatedTo(source, getKnownKeysOfTupleType(targetType), reportErrors)) {
return result;
}
}
else {
// A type S is assignable to keyof T if S is assignable to keyof C, where C is the
// simplified form of T or, if T doesn't simplify, the constraint of T.
const constraint = getSimplifiedTypeOrConstraint(targetType);
if (constraint) {
// We require Ternary.True here such that circular constraints don't cause
// false positives. For example, given 'T extends { [K in keyof T]: string }',
// 'keyof T' has itself as its constraint and produces a Ternary.Maybe when
// related to other types.
if (isRelatedTo(source, getIndexType(constraint, (target as IndexType).stringsOnly), reportErrors) === Ternary.True) {
return Ternary.True;
}
}
}
}
Expand Down
78 changes: 76 additions & 2 deletions tests/baselines/reference/variadicTuples1.errors.txt
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,29 @@ tests/cases/conformance/types/tuple/variadicTuples1.ts(169,5): error TS2322: Typ
tests/cases/conformance/types/tuple/variadicTuples1.ts(170,5): error TS2322: Type 'T' is not assignable to type '[...T]'.
The type 'readonly unknown[]' is 'readonly' and cannot be assigned to the mutable type '[...T]'.
tests/cases/conformance/types/tuple/variadicTuples1.ts(171,5): error TS4104: The type 'readonly [...T]' is 'readonly' and cannot be assigned to the mutable type '[...T]'.
tests/cases/conformance/types/tuple/variadicTuples1.ts(303,14): error TS7019: Rest parameter 'x' implicitly has an 'any[]' type.
tests/cases/conformance/types/tuple/variadicTuples1.ts(181,5): error TS2322: Type 'T' is not assignable to type '[...U]'.
Type 'string[]' is not assignable to type '[...U]'.
Target requires 1 element(s) but source may have fewer.
tests/cases/conformance/types/tuple/variadicTuples1.ts(182,5): error TS2322: Type '[...T]' is not assignable to type '[...U]'.
Type 'T' is not assignable to type 'U'.
'T' is assignable to the constraint of type 'U', but 'U' could be instantiated with a different subtype of constraint 'string[]'.
Type 'string[]' is not assignable to type 'U'.
'U' could be instantiated with an arbitrary type which could be unrelated to 'string[]'.
tests/cases/conformance/types/tuple/variadicTuples1.ts(188,5): error TS2322: Type 'T' is not assignable to type '[...T]'.
The type 'readonly string[]' is 'readonly' and cannot be assigned to the mutable type '[...T]'.
tests/cases/conformance/types/tuple/variadicTuples1.ts(190,5): error TS2322: Type 'T' is not assignable to type '[...U]'.
The type 'readonly string[]' is 'readonly' and cannot be assigned to the mutable type '[...U]'.
tests/cases/conformance/types/tuple/variadicTuples1.ts(191,5): error TS2322: Type '[...T]' is not assignable to type '[...U]'.
Type 'T' is not assignable to type 'U'.
'T' is assignable to the constraint of type 'U', but 'U' could be instantiated with a different subtype of constraint 'readonly string[]'.
Type 'readonly string[]' is not assignable to type 'U'.
'U' could be instantiated with an arbitrary type which could be unrelated to 'readonly string[]'.
tests/cases/conformance/types/tuple/variadicTuples1.ts(203,5): error TS2322: Type 'string' is not assignable to type 'keyof [1, 2, ...T]'.
Type '"2"' is not assignable to type 'number | "0" | "length" | "toString" | "toLocaleString" | "pop" | "push" | "concat" | "join" | "reverse" | "shift" | "slice" | "sort" | "splice" | "unshift" | "indexOf" | "lastIndexOf" | "every" | "some" | "forEach" | "map" | "filter" | "reduce" | "reduceRight" | "1"'.
tests/cases/conformance/types/tuple/variadicTuples1.ts(333,14): error TS7019: Rest parameter 'x' implicitly has an 'any[]' type.


==== tests/cases/conformance/types/tuple/variadicTuples1.ts (13 errors) ====
==== tests/cases/conformance/types/tuple/variadicTuples1.ts (19 errors) ====
// Variadics in tuple types

type TV0<T extends unknown[]> = [string, ...T];
Expand Down Expand Up @@ -234,6 +253,61 @@ tests/cases/conformance/types/tuple/variadicTuples1.ts(303,14): error TS7019: Re
r = m;
}

function f13<T extends string[], U extends T>(t0: T, t1: [...T], t2: [...U]) {
t0 = t1;
t0 = t2;
t1 = t0;
t1 = t2;
t2 = t0; // Error
~~
!!! error TS2322: Type 'T' is not assignable to type '[...U]'.
!!! error TS2322: Type 'string[]' is not assignable to type '[...U]'.
!!! error TS2322: Target requires 1 element(s) but source may have fewer.
t2 = t1; // Error
~~
!!! error TS2322: Type '[...T]' is not assignable to type '[...U]'.
!!! error TS2322: Type 'T' is not assignable to type 'U'.
!!! error TS2322: 'T' is assignable to the constraint of type 'U', but 'U' could be instantiated with a different subtype of constraint 'string[]'.
!!! error TS2322: Type 'string[]' is not assignable to type 'U'.
!!! error TS2322: 'U' could be instantiated with an arbitrary type which could be unrelated to 'string[]'.
}

function f14<T extends readonly string[], U extends T>(t0: T, t1: [...T], t2: [...U]) {
t0 = t1;
t0 = t2;
t1 = t0; // Error
~~
!!! error TS2322: Type 'T' is not assignable to type '[...T]'.
!!! error TS2322: The type 'readonly string[]' is 'readonly' and cannot be assigned to the mutable type '[...T]'.
t1 = t2;
t2 = t0; // Error
~~
!!! error TS2322: Type 'T' is not assignable to type '[...U]'.
!!! error TS2322: The type 'readonly string[]' is 'readonly' and cannot be assigned to the mutable type '[...U]'.
t2 = t1; // Error
~~
!!! error TS2322: Type '[...T]' is not assignable to type '[...U]'.
!!! error TS2322: Type 'T' is not assignable to type 'U'.
!!! error TS2322: 'T' is assignable to the constraint of type 'U', but 'U' could be instantiated with a different subtype of constraint 'readonly string[]'.
!!! error TS2322: Type 'readonly string[]' is not assignable to type 'U'.
!!! error TS2322: 'U' could be instantiated with an arbitrary type which could be unrelated to 'readonly string[]'.
}

function f15<T extends string[], U extends T>(k0: keyof T, k1: keyof [...T], k2: keyof [...U], k3: keyof [1, 2, ...T]) {
k0 = 'length';
k1 = 'length';
k2 = 'length';
k0 = 'slice';
k1 = 'slice';
k2 = 'slice';
k3 = '0';
k3 = '1';
k3 = '2'; // Error
~~
!!! error TS2322: Type 'string' is not assignable to type 'keyof [1, 2, ...T]'.
!!! error TS2322: Type '"2"' is not assignable to type 'number | "0" | "length" | "toString" | "toLocaleString" | "pop" | "push" | "concat" | "join" | "reverse" | "shift" | "slice" | "sort" | "splice" | "unshift" | "indexOf" | "lastIndexOf" | "every" | "some" | "forEach" | "map" | "filter" | "reduce" | "reduceRight" | "1"'.
}

// Inference between variadic tuple types

type First<T extends readonly unknown[]> = T[0];
Expand Down
60 changes: 60 additions & 0 deletions tests/baselines/reference/variadicTuples1.js
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,36 @@ function f12<T extends readonly unknown[]>(t: T, m: [...T], r: readonly [...T])
r = m;
}

function f13<T extends string[], U extends T>(t0: T, t1: [...T], t2: [...U]) {
t0 = t1;
t0 = t2;
t1 = t0;
t1 = t2;
t2 = t0; // Error
t2 = t1; // Error
}

function f14<T extends readonly string[], U extends T>(t0: T, t1: [...T], t2: [...U]) {
t0 = t1;
t0 = t2;
t1 = t0; // Error
t1 = t2;
t2 = t0; // Error
t2 = t1; // Error
}

function f15<T extends string[], U extends T>(k0: keyof T, k1: keyof [...T], k2: keyof [...U], k3: keyof [1, 2, ...T]) {
k0 = 'length';
k1 = 'length';
k2 = 'length';
k0 = 'slice';
k1 = 'slice';
k2 = 'slice';
k3 = '0';
k3 = '1';
k3 = '2'; // Error
}

// Inference between variadic tuple types

type First<T extends readonly unknown[]> = T[0];
Expand Down Expand Up @@ -414,6 +444,33 @@ function f12(t, m, r) {
r = t;
r = m;
}
function f13(t0, t1, t2) {
t0 = t1;
t0 = t2;
t1 = t0;
t1 = t2;
t2 = t0; // Error
t2 = t1; // Error
}
function f14(t0, t1, t2) {
t0 = t1;
t0 = t2;
t1 = t0; // Error
t1 = t2;
t2 = t0; // Error
t2 = t1; // Error
}
function f15(k0, k1, k2, k3) {
k0 = 'length';
k1 = 'length';
k2 = 'length';
k0 = 'slice';
k1 = 'slice';
k2 = 'slice';
k3 = '0';
k3 = '1';
k3 = '2'; // Error
}
// Inference to [...T, ...U] with implied arity for T
function curry(f) {
var a = [];
Expand Down Expand Up @@ -522,6 +579,9 @@ declare function gx2<U extends unknown[], V extends readonly unknown[]>(u: U, v:
declare function f10<T extends string[], U extends T>(x: [string, ...unknown[]], y: [string, ...T], z: [string, ...U]): void;
declare function f11<T extends unknown[]>(t: T, m: [...T], r: readonly [...T]): void;
declare function f12<T extends readonly unknown[]>(t: T, m: [...T], r: readonly [...T]): void;
declare function f13<T extends string[], U extends T>(t0: T, t1: [...T], t2: [...U]): void;
declare function f14<T extends readonly string[], U extends T>(t0: T, t1: [...T], t2: [...U]): void;
declare function f15<T extends string[], U extends T>(k0: keyof T, k1: keyof [...T], k2: keyof [...U], k3: keyof [1, 2, ...T]): void;
declare type First<T extends readonly unknown[]> = T[0];
declare type DropFirst<T extends readonly unknown[]> = T extends readonly [any, ...infer U] ? U : [...T];
declare type Last<T extends readonly unknown[]> = T extends readonly [...infer _, infer U] ? U : undefined;
Expand Down
Loading