Skip to content

Strip tags in placeholders #56458

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

Closed
wants to merge 8 commits into from
Closed
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
57 changes: 31 additions & 26 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16925,10 +16925,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}

function removeStringLiteralsMatchedByTemplateLiterals(types: Type[]) {
const templates = filter(types, t =>
!!(t.flags & TypeFlags.TemplateLiteral) &&
isPatternLiteralType(t) &&
(t as TemplateLiteralType).types.every(t => !(t.flags & TypeFlags.Intersection) || !areIntersectedTypesAvoidingPrimitiveReduction((t as IntersectionType).types))) as TemplateLiteralType[];
const templates = filter(types, t => !!(t.flags & TypeFlags.TemplateLiteral) && isPatternLiteralType(t)) as TemplateLiteralType[];
if (templates.length) {
let i = types.length;
while (i > 0) {
Expand Down Expand Up @@ -17439,20 +17436,17 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
return reduceLeft(types, (n, t) => n + getConstituentCount(t), 0);
}

function areIntersectedTypesAvoidingPrimitiveReduction(types: Type[], primitiveFlags = TypeFlags.String | TypeFlags.Number | TypeFlags.BigInt): boolean {
if (types.length !== 2) {
return false;
}
const [t1, t2] = types;
return !!(t1.flags & primitiveFlags) && t2 === emptyTypeLiteralType || !!(t2.flags & primitiveFlags) && t1 === emptyTypeLiteralType;
}

function getTypeFromIntersectionTypeNode(node: IntersectionTypeNode): Type {
const links = getNodeLinks(node);
if (!links.resolvedType) {
const aliasSymbol = getAliasSymbolForTypeNode(node);
const types = map(node.types, getTypeFromTypeNode);
const noSupertypeReduction = areIntersectedTypesAvoidingPrimitiveReduction(types);
// We perform no supertype reduction for X & {} or {} & X, where X is one of string, number, bigint,
// or a pattern literal template type. This enables union types like "a" | "b" | string & {} or
// "aa" | "ab" | `a${string}` which preserve the literal types for purposes of statement completion.
const emptyIndex = types.length === 2 ? types.indexOf(emptyTypeLiteralType) : -1;
const t = emptyIndex >= 0 ? types[1 - emptyIndex] : unknownType;
const noSupertypeReduction = !!(t.flags & (TypeFlags.String | TypeFlags.Number | TypeFlags.BigInt) || t.flags & TypeFlags.TemplateLiteral && isPatternLiteralType(t));
links.resolvedType = getIntersectionType(types, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol), noSupertypeReduction);
}
return links.resolvedType;
Expand Down Expand Up @@ -17702,7 +17696,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {

function addSpans(texts: readonly string[], types: readonly Type[]): boolean {
for (let i = 0; i < types.length; i++) {
const t = types[i];
const t = stripObjectTypeTags(types[i]);
if (t.flags & (TypeFlags.Literal | TypeFlags.Null | TypeFlags.Undefined)) {
text += getTemplateStringForType(t) || "";
text += texts[i + 1];
Expand All @@ -17725,6 +17719,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}
}

function stripObjectTypeTags(type: Type) {
if (type.flags & TypeFlags.Intersection) {
const nonObjectTypes = filter((type as IntersectionType).types, t => !(t.flags & TypeFlags.Object));
if (nonObjectTypes !== (type as IntersectionType).types) {
return getIntersectionType(nonObjectTypes);
}
}
return type;
}

function getTemplateStringForType(type: Type) {
return type.flags & TypeFlags.StringLiteral ? (type as StringLiteralType).value :
type.flags & TypeFlags.NumberLiteral ? "" + (type as NumberLiteralType).value :
Expand All @@ -17735,7 +17739,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {

function createTemplateLiteralType(texts: readonly string[], types: readonly Type[]) {
const type = createType(TypeFlags.TemplateLiteral) as TemplateLiteralType;
type.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ TypeFlags.Nullable);
type.texts = texts;
type.types = types;
return type;
Expand Down Expand Up @@ -18059,13 +18062,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}

function isPatternLiteralPlaceholderType(type: Type): boolean {
if (type.flags & TypeFlags.Intersection) {
return !isGenericType(type) && some((type as IntersectionType).types, t => !!(t.flags & (TypeFlags.Literal | TypeFlags.Nullable)) || isPatternLiteralPlaceholderType(t));
}
return !!(type.flags & (TypeFlags.Any | TypeFlags.String | TypeFlags.Number | TypeFlags.BigInt)) || isPatternLiteralType(type);
return !!(type.flags & (TypeFlags.Any | TypeFlags.String | TypeFlags.Number | TypeFlags.BigInt) ||
isPatternLiteralType(type) ||
type.flags & TypeFlags.Intersection && every((type as IntersectionType).types, isPatternLiteralType));
}

function isPatternLiteralType(type: Type) {
// A pattern literal type is a template literal or a string mapping type that contains only
// non-generic pattern literal placeholders. Assumptions are made elsewhere that pattern literal
// contain no generics. For example, pattern literal types can be key types in index signatures.
return !!(type.flags & TypeFlags.TemplateLiteral) && every((type as TemplateLiteralType).types, isPatternLiteralPlaceholderType) ||
!!(type.flags & TypeFlags.StringMapping) && isPatternLiteralPlaceholderType((type as StringMappingType).type);
}
Expand All @@ -18083,12 +18088,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}

function getGenericObjectFlags(type: Type): ObjectFlags {
if (type.flags & (TypeFlags.UnionOrIntersection | TypeFlags.TemplateLiteral)) {
if (!((type as UnionOrIntersectionType | TemplateLiteralType).objectFlags & ObjectFlags.IsGenericTypeComputed)) {
(type as UnionOrIntersectionType | TemplateLiteralType).objectFlags |= ObjectFlags.IsGenericTypeComputed |
reduceLeft((type as UnionOrIntersectionType | TemplateLiteralType).types, (flags, t) => flags | getGenericObjectFlags(t), 0);
if (type.flags & (TypeFlags.UnionOrIntersection)) {
if (!((type as UnionOrIntersectionType).objectFlags & ObjectFlags.IsGenericTypeComputed)) {
(type as UnionOrIntersectionType).objectFlags |= ObjectFlags.IsGenericTypeComputed |
reduceLeft((type as UnionOrIntersectionType).types, (flags, t) => flags | getGenericObjectFlags(t), 0);
}
return (type as UnionOrIntersectionType | TemplateLiteralType).objectFlags & ObjectFlags.IsGenericType;
return (type as UnionOrIntersectionType).objectFlags & ObjectFlags.IsGenericType;
}
if (type.flags & TypeFlags.Substitution) {
if (!((type as SubstitutionType).objectFlags & ObjectFlags.IsGenericTypeComputed)) {
Expand All @@ -18098,7 +18103,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
return (type as SubstitutionType).objectFlags & ObjectFlags.IsGenericType;
}
return (type.flags & TypeFlags.InstantiableNonPrimitive || isGenericMappedType(type) || isGenericTupleType(type) ? ObjectFlags.IsGenericObjectType : 0) |
(type.flags & (TypeFlags.InstantiableNonPrimitive | TypeFlags.Index | TypeFlags.StringMapping) && !isPatternLiteralType(type) ? ObjectFlags.IsGenericIndexType : 0);
(type.flags & (TypeFlags.InstantiableNonPrimitive | TypeFlags.Index | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) && !isPatternLiteralType(type) ? ObjectFlags.IsGenericIndexType : 0);
}

function getSimplifiedType(type: Type, writing: boolean): Type {
Expand Down Expand Up @@ -24768,7 +24773,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
objectFlags & ObjectFlags.Anonymous && type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.Class | SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral) && type.symbol.declarations ||
objectFlags & (ObjectFlags.Mapped | ObjectFlags.ReverseMapped | ObjectFlags.ObjectRestType | ObjectFlags.InstantiationExpressionType)
) ||
type.flags & (TypeFlags.UnionOrIntersection | TypeFlags.TemplateLiteral) && !(type.flags & TypeFlags.EnumLiteral) && !isNonGenericTopLevelType(type) && some((type as UnionOrIntersectionType | TemplateLiteralType).types, couldContainTypeVariables));
type.flags & TypeFlags.UnionOrIntersection && !(type.flags & TypeFlags.EnumLiteral) && !isNonGenericTopLevelType(type) && some((type as UnionOrIntersectionType).types, couldContainTypeVariables));
if (type.flags & TypeFlags.ObjectFlagsType) {
(type as ObjectFlagsType).objectFlags |= ObjectFlags.CouldContainTypeVariablesComputed | (result ? ObjectFlags.CouldContainTypeVariables : 0);
}
Expand Down
8 changes: 3 additions & 5 deletions src/compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6130,7 +6130,7 @@ export const enum TypeFlags {
Instantiable = InstantiableNonPrimitive | InstantiablePrimitive,
StructuredOrInstantiable = StructuredType | Instantiable,
/** @internal */
ObjectFlagsType = Any | Nullable | Never | Object | Union | Intersection | TemplateLiteral,
ObjectFlagsType = Any | Nullable | Never | Object | Union | Intersection,
/** @internal */
Simplifiable = IndexedAccess | Conditional,
/** @internal */
Expand Down Expand Up @@ -6289,7 +6289,7 @@ export const enum ObjectFlags {
/** @internal */
IdenticalBaseTypeExists = 1 << 26, // has a defined cachedEquivalentBaseType member

// Flags that require TypeFlags.UnionOrIntersection, TypeFlags.Substitution, or TypeFlags.TemplateLiteral
// Flags that require TypeFlags.UnionOrIntersection or TypeFlags.Substitution
/** @internal */
IsGenericTypeComputed = 1 << 21, // IsGenericObjectType flag has been computed
/** @internal */
Expand All @@ -6316,7 +6316,7 @@ export const enum ObjectFlags {
}

/** @internal */
export type ObjectFlagsType = NullableType | ObjectType | UnionType | IntersectionType | TemplateLiteralType;
export type ObjectFlagsType = NullableType | ObjectType | UnionType | IntersectionType;

// Object types (TypeFlags.ObjectType)
// dprint-ignore
Expand Down Expand Up @@ -6675,8 +6675,6 @@ export interface ConditionalType extends InstantiableType {
}

export interface TemplateLiteralType extends InstantiableType {
/** @internal */
objectFlags: ObjectFlags;
texts: readonly string[]; // Always one element longer than types
types: readonly Type[]; // Always at least one element
}
Expand Down
10 changes: 5 additions & 5 deletions tests/baselines/reference/templateLiteralIntersection.types
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ type OriginA1 = `${A}`
>OriginA1 : "a"

type OriginA2 = `${MixA}`
>OriginA2 : `${MixA}`
>OriginA2 : "a"

type B = `${typeof a}`
>B : "a"
Expand All @@ -32,23 +32,23 @@ type OriginB1 = `${B}`
>OriginB1 : "a"

type OriginB2 = `${MixB}`
>OriginB2 : `${MixB}`
>OriginB2 : "a"

type MixC = { foo: string } & A
>MixC : { foo: string; } & "a"
>foo : string

type OriginC = `${MixC}`
>OriginC : `${MixC}`
>OriginC : "a"

type MixD<T extends string> =
>MixD : `${T & { foo: string; }}`
>MixD : `${T}`

`${T & { foo: string }}`
>foo : string

type OriginD = `${MixD<A & { foo: string }> & { foo: string }}`;
>OriginD : `${`${"a" & { foo: string; } & { foo: string; }}` & { foo: string; }}`
>OriginD : "a"
>foo : string
>foo : string

Expand Down
Original file line number Diff line number Diff line change
@@ -1,20 +1,17 @@
templateLiteralIntersection2.ts(7,12): error TS2345: Argument of type '"foo/bar"' is not assignable to parameter of type '`${Path}/${Path}`'.
templateLiteralIntersection2.ts(20,10): error TS2345: Argument of type '""' is not assignable to parameter of type '`a${string}` & `${string}a`'.
Type '""' is not assignable to type '`a${string}`'.
templateLiteralIntersection2.ts(22,10): error TS2345: Argument of type '"ab"' is not assignable to parameter of type '`a${string}` & `${string}a`'.
Type '"ab"' is not assignable to type '`${string}a`'.


==== templateLiteralIntersection2.ts (3 errors) ====
==== templateLiteralIntersection2.ts (2 errors) ====
type Path = string & { _pathBrand: any };

type JoinedPath = `${Path}/${Path}`;

declare function joinedPath(p: JoinedPath): void;

joinedPath("foo/bar");
~~~~~~~~~
!!! error TS2345: Argument of type '"foo/bar"' is not assignable to parameter of type '`${Path}/${Path}`'.

declare const somePath: Path;

Expand Down
10 changes: 5 additions & 5 deletions tests/baselines/reference/templateLiteralIntersection2.types
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,24 @@ type Path = string & { _pathBrand: any };
>_pathBrand : any

type JoinedPath = `${Path}/${Path}`;
>JoinedPath : `${Path}/${Path}`
>JoinedPath : `${string}/${string}`

declare function joinedPath(p: JoinedPath): void;
>joinedPath : (p: JoinedPath) => void
>p : `${Path}/${Path}`
>p : `${string}/${string}`

joinedPath("foo/bar");
>joinedPath("foo/bar") : void
>joinedPath : (p: `${Path}/${Path}`) => void
>joinedPath : (p: `${string}/${string}`) => void
>"foo/bar" : "foo/bar"

declare const somePath: Path;
>somePath : Path

joinedPath(`${somePath}/${somePath}`);
>joinedPath(`${somePath}/${somePath}`) : void
>joinedPath : (p: `${Path}/${Path}`) => void
>`${somePath}/${somePath}` : `${Path}/${Path}`
>joinedPath : (p: `${string}/${string}`) => void
>`${somePath}/${somePath}` : `${string}/${string}`
>somePath : Path
>somePath : Path

Expand Down
6 changes: 3 additions & 3 deletions tests/baselines/reference/templateLiteralIntersection3.types
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,19 @@ options1[`foo/${path}`] = false;
>options1[`foo/${path}`] = false : false
>options1[`foo/${path}`] : boolean
>options1 : { prop: number; } & { [k: string]: boolean; }
>`foo/${path}` : `foo/${Path}`
>`foo/${path}` : `foo/${string}`
>path : Path
>false : false


// Lowercase<`foo/${Path}`> => `foo/${Lowercase<Path>}`
declare const lowercasePath: Lowercase<`foo/${Path}`>;
>lowercasePath : `foo/${Lowercase<`${Path}`>}`
>lowercasePath : `foo/${Lowercase<string>}`

options1[lowercasePath] = false;
>options1[lowercasePath] = false : false
>options1[lowercasePath] : boolean
>options1 : { prop: number; } & { [k: string]: boolean; }
>lowercasePath : `foo/${Lowercase<`${Path}`>}`
>lowercasePath : `foo/${Lowercase<string>}`
>false : false

Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ templateLiteralTypesPatterns.ts(129,9): error TS2345: Argument of type '"1.1e-10
templateLiteralTypesPatterns.ts(140,1): error TS2322: Type '`a${string}`' is not assignable to type '`a${number}`'.
templateLiteralTypesPatterns.ts(141,1): error TS2322: Type '"bno"' is not assignable to type '`a${any}`'.
templateLiteralTypesPatterns.ts(160,7): error TS2322: Type '"anything"' is not assignable to type '`${number} ${number}`'.
templateLiteralTypesPatterns.ts(211,5): error TS2345: Argument of type '"abcTest"' is not assignable to parameter of type '`${`a${string}` & `${string}a`}Test`'.
templateLiteralTypesPatterns.ts(215,5): error TS2345: Argument of type '"abcTest"' is not assignable to parameter of type '`${`a${string}` & `${string}a`}Test`'.


==== templateLiteralTypesPatterns.ts (58 errors) ====
Expand Down Expand Up @@ -376,10 +376,14 @@ templateLiteralTypesPatterns.ts(211,5): error TS2345: Argument of type '"abcTest
}

// repro from https://github.com/microsoft/TypeScript/issues/54177#issuecomment-1538436654
function conversionTest(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${string & {}}Downcast`) {}
function conversionTest(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${string}Downcast` & {}) {}
conversionTest("testDowncast");
function conversionTest2(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${{} & string}Downcast`) {}
function conversionTest2(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | {} & `${string}Downcast`) {}
conversionTest2("testDowncast");
function conversionTest3(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${string & {}}Downcast`) {}
conversionTest3("testDowncast");
function conversionTest4(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${{} & string}Downcast`) {}
conversionTest4("testDowncast");

function foo(str: `${`a${string}` & `${string}a`}Test`) {}
foo("abaTest"); // ok
Expand Down
12 changes: 10 additions & 2 deletions tests/baselines/reference/templateLiteralTypesPatterns.js
Original file line number Diff line number Diff line change
Expand Up @@ -204,10 +204,14 @@ export abstract class BB {
}

// repro from https://github.com/microsoft/TypeScript/issues/54177#issuecomment-1538436654
function conversionTest(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${string & {}}Downcast`) {}
function conversionTest(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${string}Downcast` & {}) {}
conversionTest("testDowncast");
function conversionTest2(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${{} & string}Downcast`) {}
function conversionTest2(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | {} & `${string}Downcast`) {}
conversionTest2("testDowncast");
function conversionTest3(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${string & {}}Downcast`) {}
conversionTest3("testDowncast");
function conversionTest4(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${{} & string}Downcast`) {}
conversionTest4("testDowncast");

function foo(str: `${`a${string}` & `${string}a`}Test`) {}
foo("abaTest"); // ok
Expand Down Expand Up @@ -367,6 +371,10 @@ function conversionTest(groupName) { }
conversionTest("testDowncast");
function conversionTest2(groupName) { }
conversionTest2("testDowncast");
function conversionTest3(groupName) { }
conversionTest3("testDowncast");
function conversionTest4(groupName) { }
conversionTest4("testDowncast");
function foo(str) { }
foo("abaTest"); // ok
foo("abcTest"); // error
Loading