Skip to content

Fix noUncheckedIndexedAccess with tuple rest types and generic index types #40681

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
Show file tree
Hide file tree
Changes from 2 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
38 changes: 15 additions & 23 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,15 +180,6 @@ namespace ts {
IsForSignatureHelp = 1 << 4, // Call resolution for purposes of signature help
}

const enum AccessFlags {
None = 0,
NoIndexSignatures = 1 << 0,
Writing = 1 << 1,
CacheSymbol = 1 << 2,
NoTupleBoundsCheck = 1 << 3,
ExpressionPosition = 1 << 4,
}

const enum SignatureCheckMode {
BivariantCallback = 1 << 0,
StrictCallback = 1 << 1,
Expand Down Expand Up @@ -10744,14 +10735,14 @@ namespace ts {
function getConstraintFromIndexedAccess(type: IndexedAccessType) {
const indexConstraint = getSimplifiedTypeOrConstraint(type.indexType);
if (indexConstraint && indexConstraint !== type.indexType) {
const indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint);
const indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint, /*accessNode*/ undefined, type.accessFlags);
if (indexedAccess) {
return indexedAccess;
}
}
const objectConstraint = getSimplifiedTypeOrConstraint(type.objectType);
if (objectConstraint && objectConstraint !== type.objectType) {
return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType);
return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType, /*accessNode*/ undefined, type.accessFlags);
}
return undefined;
}
Expand Down Expand Up @@ -10949,7 +10940,7 @@ namespace ts {
if (t.flags & TypeFlags.IndexedAccess) {
const baseObjectType = getBaseConstraint((<IndexedAccessType>t).objectType);
const baseIndexType = getBaseConstraint((<IndexedAccessType>t).indexType);
const baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType);
const baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, /*accessNode*/ undefined, (t as IndexedAccessType).accessFlags);
return baseIndexedAccess && getBaseConstraint(baseIndexedAccess);
}
if (t.flags & TypeFlags.Conditional) {
Expand Down Expand Up @@ -13592,12 +13583,13 @@ namespace ts {
return result;
}

function createIndexedAccessType(objectType: Type, indexType: Type, aliasSymbol: Symbol | undefined, aliasTypeArguments: readonly Type[] | undefined) {
function createIndexedAccessType(objectType: Type, indexType: Type, aliasSymbol: Symbol | undefined, aliasTypeArguments: readonly Type[] | undefined, accessFlags: AccessFlags) {
const type = <IndexedAccessType>createType(TypeFlags.IndexedAccess);
type.objectType = objectType;
type.indexType = indexType;
type.aliasSymbol = aliasSymbol;
type.aliasTypeArguments = aliasTypeArguments;
type.accessFlags = accessFlags;
return type;
}

Expand Down Expand Up @@ -13650,6 +13642,10 @@ namespace ts {
function getPropertyTypeForIndexType(originalObjectType: Type, objectType: Type, indexType: Type, fullIndexType: Type, suppressNoImplicitAnyError: boolean, accessNode: ElementAccessExpression | IndexedAccessTypeNode | PropertyName | BindingName | SyntheticExpression | undefined, accessFlags: AccessFlags, reportDeprecated?: boolean) {
const accessExpression = accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode : undefined;
const propName = accessNode && isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode);
const shouldIncludeUndefined =
compilerOptions.noUncheckedIndexedAccess &&
(accessFlags & (AccessFlags.Writing | AccessFlags.ExpressionPosition)) === AccessFlags.ExpressionPosition;

if (propName !== undefined) {
const prop = getPropertyOfType(objectType, propName);
if (prop) {
Expand Down Expand Up @@ -13687,7 +13683,10 @@ namespace ts {
}
}
errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, IndexKind.Number));
return mapType(objectType, t => getRestTypeOfTupleType(<TupleTypeReference>t) || undefinedType);
return mapType(objectType, t => {
const restType = getRestTypeOfTupleType(<TupleTypeReference>t) || undefinedType;
return shouldIncludeUndefined ? getUnionType([restType, undefinedType]) : restType;
});
}
}
if (!(indexType.flags & TypeFlags.Nullable) && isTypeAssignableToKind(indexType, TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.ESSymbolLike)) {
Expand All @@ -13703,9 +13702,6 @@ namespace ts {
}
return undefined;
}
const shouldIncludeUndefined =
compilerOptions.noUncheckedIndexedAccess &&
(accessFlags & (AccessFlags.Writing | AccessFlags.ExpressionPosition)) === AccessFlags.ExpressionPosition;
if (accessNode && !isTypeAssignableToKind(indexType, TypeFlags.String | TypeFlags.Number)) {
const indexNode = getIndexNodeForAccessExpression(accessNode);
error(indexNode, Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
Expand Down Expand Up @@ -13976,10 +13972,6 @@ namespace ts {
return wildcardType;
}

const shouldIncludeUndefined =
compilerOptions.noUncheckedIndexedAccess &&
(accessFlags & (AccessFlags.Writing | AccessFlags.ExpressionPosition)) === AccessFlags.ExpressionPosition;

// If the object type has a string index signature and no other members we know that the result will
// always be the type of that index signature and we can simplify accordingly.
if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & TypeFlags.Nullable) && isTypeAssignableToKind(indexType, TypeFlags.String | TypeFlags.Number)) {
Expand All @@ -14001,10 +13993,10 @@ namespace ts {
const id = objectType.id + "," + indexType.id;
let type = indexedAccessTypes.get(id);
if (!type) {
indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments));
indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, accessFlags));
}

return shouldIncludeUndefined ? getUnionType([type, undefinedType]) : type;
return 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.

At this point, we don’t yet know whether the index type will be constrained to something that resolves to property signatures or index signatures, so we can’t return a union with undefined. But when we come back to do the deferred checking of the indexed access type we saved, we’ve lost the accessFlags that indicate that this is a position where undefined should be included in the type.

As I’m writing this, I’m realizing that this is probably broken for generic indexed access types that get used both for reading and for writing, so converting back to draft.

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 only easy way I could find to fix this was creating separate IndexedAccessTypes (and keying the cache) depending on whether it was an expression where --noUncheckedIndexedAccess could have an effect or not. So in effect, in

function<T extends string>(key: T) {
  obj[key] = undefined;
  return obj[key];
}

the two usages of obj[key] have two separate types. (This only happens when the object type and/or the index type is generic.) I think this is technically possible to avoid, but would involve a lot of inexpedient threading of accessFlags (or some parameter based on it) through a bunch of functions.

}
// In the following we resolve T[K] to the type of the property in T selected by K.
// We treat boolean as different from other unions to improve errors;
Expand Down
12 changes: 12 additions & 0 deletions src/compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5317,11 +5317,23 @@ namespace ts {
resolvedDefaultType?: Type;
}

/* @internal */
export const enum AccessFlags {
None = 0,
NoIndexSignatures = 1 << 0,
Writing = 1 << 1,
CacheSymbol = 1 << 2,
NoTupleBoundsCheck = 1 << 3,
ExpressionPosition = 1 << 4,
}

// Indexed access types (TypeFlags.IndexedAccess)
// Possible forms are T[xxx], xxx[T], or xxx[keyof T], where T is a type variable
export interface IndexedAccessType extends InstantiableType {
objectType: Type;
indexType: Type;
/* @internal */
accessFlags: AccessFlags;
constraint?: Type;
simplifiedForReading?: Type;
simplifiedForWriting?: Type;
Expand Down
26 changes: 25 additions & 1 deletion tests/baselines/reference/noUncheckedIndexedAccess.errors.txt
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,14 @@ tests/cases/conformance/pedantic/noUncheckedIndexedAccess.ts(63,5): error TS2322
tests/cases/conformance/pedantic/noUncheckedIndexedAccess.ts(79,7): error TS2322: Type 'number | boolean | undefined' is not assignable to type 'number | boolean'.
Type 'undefined' is not assignable to type 'number | boolean'.
tests/cases/conformance/pedantic/noUncheckedIndexedAccess.ts(85,1): error TS2322: Type 'undefined' is not assignable to type 'string'.
tests/cases/conformance/pedantic/noUncheckedIndexedAccess.ts(90,7): error TS2322: Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
tests/cases/conformance/pedantic/noUncheckedIndexedAccess.ts(97,71): error TS2322: Type '{ [key: string]: string; a: string; b: string; }[Key]' is not assignable to type 'string'.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.


==== tests/cases/conformance/pedantic/noUncheckedIndexedAccess.ts (28 errors) ====
==== tests/cases/conformance/pedantic/noUncheckedIndexedAccess.ts (30 errors) ====
type CheckBooleanOnly<T extends boolean> = any;
// Validate CheckBooleanOnly works - should error
type T_ERR1 = CheckBooleanOnly<boolean | undefined>;
Expand Down Expand Up @@ -216,4 +221,23 @@ tests/cases/conformance/pedantic/noUncheckedIndexedAccess.ts(85,1): error TS2322
symbolMap[s] = undefined; // Should error
~~~~~~~~~~~~
!!! error TS2322: Type 'undefined' is not assignable to type 'string'.

// Variadic tuples
declare const nonEmptyStringArray: [string, ...string[]];
const variadicOk1: string = nonEmptyStringArray[0]; // Should OK
const variadicError1: string = nonEmptyStringArray[1]; // Should error
~~~~~~~~~~~~~~
!!! error TS2322: Type 'string | undefined' is not assignable to type 'string'.
!!! error TS2322: Type 'undefined' is not assignable to type 'string'.

// Generic index type
declare const myRecord1: { a: string; b: string };
declare const myRecord2: { a: string; b: string, [key: string]: string };
const fn1 = <Key extends keyof typeof myRecord1>(key: Key): string => myRecord1[key]; // Should OK
const fn2 = <Key extends keyof typeof myRecord1>(key: Key): string => myRecord2[key]; // Should OK
const fn3 = <Key extends keyof typeof myRecord2>(key: Key): string => myRecord2[key]; // Should error
~~~~~~~~~~~~~~
!!! error TS2322: Type '{ [key: string]: string; a: string; b: string; }[Key]' is not assignable to type 'string'.
!!! error TS2322: Type 'string | undefined' is not assignable to type 'string'.
!!! error TS2322: Type 'undefined' is not assignable to type 'string'.

17 changes: 17 additions & 0 deletions tests/baselines/reference/noUncheckedIndexedAccess.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,18 @@ declare const s: unique symbol;
declare const symbolMap: { [s]: string };
const e15: string = symbolMap[s]; // Should OK
symbolMap[s] = undefined; // Should error

// Variadic tuples
declare const nonEmptyStringArray: [string, ...string[]];
const variadicOk1: string = nonEmptyStringArray[0]; // Should OK
const variadicError1: string = nonEmptyStringArray[1]; // Should error

// Generic index type
declare const myRecord1: { a: string; b: string };
declare const myRecord2: { a: string; b: string, [key: string]: string };
const fn1 = <Key extends keyof typeof myRecord1>(key: Key): string => myRecord1[key]; // Should OK
const fn2 = <Key extends keyof typeof myRecord1>(key: Key): string => myRecord2[key]; // Should OK
const fn3 = <Key extends keyof typeof myRecord2>(key: Key): string => myRecord2[key]; // Should error


//// [noUncheckedIndexedAccess.js]
Expand Down Expand Up @@ -158,3 +170,8 @@ obj1[z];
var f1 = strMapUnion["foo"];
var e15 = symbolMap[s]; // Should OK
symbolMap[s] = undefined; // Should error
var variadicOk1 = nonEmptyStringArray[0]; // Should OK
var variadicError1 = nonEmptyStringArray[1]; // Should error
var fn1 = function (key) { return myRecord1[key]; }; // Should OK
var fn2 = function (key) { return myRecord2[key]; }; // Should OK
var fn3 = function (key) { return myRecord2[key]; }; // Should error
52 changes: 52 additions & 0 deletions tests/baselines/reference/noUncheckedIndexedAccess.symbols
Original file line number Diff line number Diff line change
Expand Up @@ -287,3 +287,55 @@ symbolMap[s] = undefined; // Should error
>s : Symbol(s, Decl(noUncheckedIndexedAccess.ts, 81, 13))
>undefined : Symbol(undefined)

// Variadic tuples
declare const nonEmptyStringArray: [string, ...string[]];
>nonEmptyStringArray : Symbol(nonEmptyStringArray, Decl(noUncheckedIndexedAccess.ts, 87, 13))

const variadicOk1: string = nonEmptyStringArray[0]; // Should OK
>variadicOk1 : Symbol(variadicOk1, Decl(noUncheckedIndexedAccess.ts, 88, 5))
>nonEmptyStringArray : Symbol(nonEmptyStringArray, Decl(noUncheckedIndexedAccess.ts, 87, 13))
>0 : Symbol(0)

const variadicError1: string = nonEmptyStringArray[1]; // Should error
>variadicError1 : Symbol(variadicError1, Decl(noUncheckedIndexedAccess.ts, 89, 5))
>nonEmptyStringArray : Symbol(nonEmptyStringArray, Decl(noUncheckedIndexedAccess.ts, 87, 13))

// Generic index type
declare const myRecord1: { a: string; b: string };
>myRecord1 : Symbol(myRecord1, Decl(noUncheckedIndexedAccess.ts, 92, 13))
>a : Symbol(a, Decl(noUncheckedIndexedAccess.ts, 92, 26))
>b : Symbol(b, Decl(noUncheckedIndexedAccess.ts, 92, 37))

declare const myRecord2: { a: string; b: string, [key: string]: string };
>myRecord2 : Symbol(myRecord2, Decl(noUncheckedIndexedAccess.ts, 93, 13))
>a : Symbol(a, Decl(noUncheckedIndexedAccess.ts, 93, 26))
>b : Symbol(b, Decl(noUncheckedIndexedAccess.ts, 93, 37))
>key : Symbol(key, Decl(noUncheckedIndexedAccess.ts, 93, 50))

const fn1 = <Key extends keyof typeof myRecord1>(key: Key): string => myRecord1[key]; // Should OK
>fn1 : Symbol(fn1, Decl(noUncheckedIndexedAccess.ts, 94, 5))
>Key : Symbol(Key, Decl(noUncheckedIndexedAccess.ts, 94, 13))
>myRecord1 : Symbol(myRecord1, Decl(noUncheckedIndexedAccess.ts, 92, 13))
>key : Symbol(key, Decl(noUncheckedIndexedAccess.ts, 94, 49))
>Key : Symbol(Key, Decl(noUncheckedIndexedAccess.ts, 94, 13))
>myRecord1 : Symbol(myRecord1, Decl(noUncheckedIndexedAccess.ts, 92, 13))
>key : Symbol(key, Decl(noUncheckedIndexedAccess.ts, 94, 49))

const fn2 = <Key extends keyof typeof myRecord1>(key: Key): string => myRecord2[key]; // Should OK
>fn2 : Symbol(fn2, Decl(noUncheckedIndexedAccess.ts, 95, 5))
>Key : Symbol(Key, Decl(noUncheckedIndexedAccess.ts, 95, 13))
>myRecord1 : Symbol(myRecord1, Decl(noUncheckedIndexedAccess.ts, 92, 13))
>key : Symbol(key, Decl(noUncheckedIndexedAccess.ts, 95, 49))
>Key : Symbol(Key, Decl(noUncheckedIndexedAccess.ts, 95, 13))
>myRecord2 : Symbol(myRecord2, Decl(noUncheckedIndexedAccess.ts, 93, 13))
>key : Symbol(key, Decl(noUncheckedIndexedAccess.ts, 95, 49))

const fn3 = <Key extends keyof typeof myRecord2>(key: Key): string => myRecord2[key]; // Should error
>fn3 : Symbol(fn3, Decl(noUncheckedIndexedAccess.ts, 96, 5))
>Key : Symbol(Key, Decl(noUncheckedIndexedAccess.ts, 96, 13))
>myRecord2 : Symbol(myRecord2, Decl(noUncheckedIndexedAccess.ts, 93, 13))
>key : Symbol(key, Decl(noUncheckedIndexedAccess.ts, 96, 49))
>Key : Symbol(Key, Decl(noUncheckedIndexedAccess.ts, 96, 13))
>myRecord2 : Symbol(myRecord2, Decl(noUncheckedIndexedAccess.ts, 93, 13))
>key : Symbol(key, Decl(noUncheckedIndexedAccess.ts, 96, 49))

55 changes: 55 additions & 0 deletions tests/baselines/reference/noUncheckedIndexedAccess.types
Original file line number Diff line number Diff line change
Expand Up @@ -351,3 +351,58 @@ symbolMap[s] = undefined; // Should error
>s : unique symbol
>undefined : undefined

// Variadic tuples
declare const nonEmptyStringArray: [string, ...string[]];
>nonEmptyStringArray : [string, ...string[]]

const variadicOk1: string = nonEmptyStringArray[0]; // Should OK
>variadicOk1 : string
>nonEmptyStringArray[0] : string
>nonEmptyStringArray : [string, ...string[]]
>0 : 0

const variadicError1: string = nonEmptyStringArray[1]; // Should error
>variadicError1 : string
>nonEmptyStringArray[1] : string | undefined
>nonEmptyStringArray : [string, ...string[]]
>1 : 1

// Generic index type
declare const myRecord1: { a: string; b: string };
>myRecord1 : { a: string; b: string; }
>a : string
>b : string

declare const myRecord2: { a: string; b: string, [key: string]: string };
>myRecord2 : { [key: string]: string; a: string; b: string; }
>a : string
>b : string
>key : string

const fn1 = <Key extends keyof typeof myRecord1>(key: Key): string => myRecord1[key]; // Should OK
>fn1 : <Key extends "a" | "b">(key: Key) => string
><Key extends keyof typeof myRecord1>(key: Key): string => myRecord1[key] : <Key extends "a" | "b">(key: Key) => string
>myRecord1 : { a: string; b: string; }
>key : Key
>myRecord1[key] : { a: string; b: string; }[Key]
>myRecord1 : { a: string; b: string; }
>key : Key

const fn2 = <Key extends keyof typeof myRecord1>(key: Key): string => myRecord2[key]; // Should OK
>fn2 : <Key extends "a" | "b">(key: Key) => string
><Key extends keyof typeof myRecord1>(key: Key): string => myRecord2[key] : <Key extends "a" | "b">(key: Key) => string
>myRecord1 : { a: string; b: string; }
>key : Key
>myRecord2[key] : { [key: string]: string; a: string; b: string; }[Key]
>myRecord2 : { [key: string]: string; a: string; b: string; }
>key : Key

const fn3 = <Key extends keyof typeof myRecord2>(key: Key): string => myRecord2[key]; // Should error
>fn3 : <Key extends string | number>(key: Key) => string
><Key extends keyof typeof myRecord2>(key: Key): string => myRecord2[key] : <Key extends string | number>(key: Key) => string
>myRecord2 : { [key: string]: string; a: string; b: string; }
>key : Key
>myRecord2[key] : { [key: string]: string; a: string; b: string; }[Key]
>myRecord2 : { [key: string]: string; a: string; b: string; }
>key : Key

12 changes: 12 additions & 0 deletions tests/cases/conformance/pedantic/noUncheckedIndexedAccess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,15 @@ declare const s: unique symbol;
declare const symbolMap: { [s]: string };
const e15: string = symbolMap[s]; // Should OK
symbolMap[s] = undefined; // Should error

// Variadic tuples
declare const nonEmptyStringArray: [string, ...string[]];
const variadicOk1: string = nonEmptyStringArray[0]; // Should OK
const variadicError1: string = nonEmptyStringArray[1]; // Should error

// Generic index type
declare const myRecord1: { a: string; b: string };
declare const myRecord2: { a: string; b: string, [key: string]: string };
const fn1 = <Key extends keyof typeof myRecord1>(key: Key): string => myRecord1[key]; // Should OK
const fn2 = <Key extends keyof typeof myRecord1>(key: Key): string => myRecord2[key]; // Should OK
const fn3 = <Key extends keyof typeof myRecord2>(key: Key): string => myRecord2[key]; // Should error