iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📂

Intrinsic Keywords and String Mapped Types Quietly Added in TypeScript 4.1

に公開

In TypeScript 4.1, as a new feature accompanying key remapping in mapped types and template literal types, types such as Uppercase were added to the standard library.

// type Str = "FOOBAR"
type Str = Uppercase<"foobar">;

As seen in the example above, the Uppercase type is a type function that takes a single string. When a string literal type is passed, it returns a string literal type where all lowercase letters in that string are converted to uppercase. Others include Lowercase, Capitalize, and Uncapitalize.

These types have their definitions in the standard library (lib/es5.d.ts). That is where the intrinsic keyword is used. The following is a quote from the standard library as of TypeScript 4.1.

/**
 * Convert string literal type to uppercase
 */
type Uppercase<S extends string> = intrinsic;

/**
 * Convert string literal type to lowercase
 */
type Lowercase<S extends string> = intrinsic;

/**
 * Convert first character of string literal type to uppercase
 */
type Capitalize<S extends string> = intrinsic;

/**
 * Convert first character of string literal type to lowercase
 */
type Uncapitalize<S extends string> = intrinsic;

What is the intrinsic keyword?

Looking at these type definitions, they seem quite mysterious. The right side of the = is always intrinsic. This means that the implementation is hidden as an internal compiler implementation. In other words, it represents special functionality that cannot be expressed with normal TypeScript type definitions. If you use JavaScript, you might have experienced seeing function log() { [native code] } when trying to display the contents of a built-in function, meaning the function's contents were hidden. Think of it as something similar.

The necessity of the intrinsic keyword

TypeScript 4.1 was set to implement string case conversion functionality, but the initial implementation actually did not use intrinsic. Instead, it was designed to use a new syntax with four keywords: uppercase, lowercase, capitalize, and uncapitalize (#40336).

// Old method
// type Str = "FOOBAR"
type Str = uppercase "foobar";

The drawback of this old method was that the syntax would increase every time a new built-in type function was implemented. In the old method, four types of new syntax were added just to achieve four types of string manipulation. TypeScript (or specifically Anders Hejlsberg, who is primarily responsible for implementing new TypeScript features) tends to prefer functional designs that can handle various use cases with minimal features, and four types of new syntax existing solely for string processing went against that philosophy.

The alternative intrinsic keyword is minimal, introducing only one new keyword. Furthermore, future functional expansions can also be handled with this intrinsic keyword.

Behavior of the intrinsic keyword

Starting from TypeScript 4.1, intrinsic has become a new keyword. Therefore, in TypeScript 4.1, code like the following will result in a compilation error (this worked in TypeScript 4.0). By the way, type intrinsic = ... seems to be simply ignored without error.

type intrinsic = string;
// Error: The 'intrinsic' keyword can only be used to declare compiler provided intrinsic types.
type A = intrinsic;

intrinsic is a special type defined within the compiler, and its substance is determined by the type name and number of type arguments given to intrinsic. For example, you can use intrinsic yourself as follows:

function foo() {
    type Uppercase<T> = intrinsic;
    // type T = "FOO"
    type T = Uppercase<"foo">
}

The reason it is intentionally placed inside the function foo is to create a separate scope so that it does not conflict with the globally defined Uppercase. By declaring a type alias (type declaration) named Uppercase with one type argument as intrinsic in this way, you can use intrinsic without causing a compilation error. This process is written in the TypeScript compiler as follows (quoted from src/compiler/checker.ts in TypeScript commit eca8957430bf52cfdfa2bfe03c9431682da6a558. Subsequent quotes are the same):

const type = getDeclaredTypeOfSymbol(symbol);
if (type === intrinsicMarkerType && intrinsicTypeKinds.has(symbol.escapedName as string) && typeArguments && typeArguments.length === 1) {
    return getStringMappingType(symbol, typeArguments[0]);
}

The intrinsicMarkerType mentioned here is the special internal compiler type given to the intrinsic keyword, and intrinsicTypeKinds is the list of names supported by intrinsic. Currently, this includes Uppercase, along with Lowercase, Capitalize, and Uncapitalize. Furthermore, there is a check for the number of typeArguments, indicating that there must be exactly one type variable. This means that type Uppercase<T> = intrinsic; is acceptable, but something like type Uppercase<U, T> = intrinsic; will not be recognized. This is because all intrinsic type functions currently defined are single-argument ones, and it is expected to be changed accordingly if intrinsic type functions with two or more arguments appear in the future.

The essence of the Uppercase type inside the compiler is always intrinsicMarkerType as stated in the type definition, and when Uppercase is used like Uppercase<"foo">, the logic quoted above runs and intrinsicMarkerType is resolved.

The code mentions getStringMappedType, and this function primarily has two roles. One is to immediately apply the conversion to string literal types. The fact that T becomes the "FOO" type in the previous code is due to this functionality.

// type T = "FOO"
type T = Uppercase<"foo">

The other role is to generate a new type called string mapped type. This occurs when T in Uppercase<T> is another type variable. You can think of a String mapped type as a concept on the same level as conditional types, index access types, or mapped types. However, while those have dedicated syntax, the string mapped type occurs only through intrinsic.

String Mapped Type

Let's take a closer look at the string mapped type that was introduced here. One of the reasons this type exists is to allow features like Uppercase to be used with type variables.

function toUpperCase<T extends string>(str: T) {
    type Mapped = Uppercase<T>;
    return str.toUpperCase() as Mapped;
}

// const str: "PIKACHU"
const str = toUpperCase("pikachu");

In this code, the return value of the function toUpperCase is Uppercase<T>. When this function is actually called as toUpperCase("pikachu"), the type argument T is inferred as the "pikachu" type. As a result, the return value Uppercase<T> becomes Uppercase<"pikachu">, which is then resolved to the "PIKACHU" type. In this way, string mapped types are used internally to enable features like Uppercase within function interfaces that include type arguments.

String mapped type and type inference

Many types in TypeScript support type inference, especially inference of type arguments. A typical example is template literal types.

// type Rest = "def"
type Rest = "abcdef" extends `abc${infer S}` ? S : never;

// type Rest2 = never
type Rest2 = "aaaaaa" extends `abc${infer S}` ? S : never;

In this manner, TypeScript needs to be able to evaluate conditions like "abcdef" extends abc${infer S}`` and infer S as needed. Although infer was used here, the same applies when inferring type arguments from arguments given to a function.

Here, matching "abcdef" or "aaaaaa" against `abc${infer S}` to perform condition evaluation and S inference is part of the functionality of template literal types.

So, what about the case of string mapped types? In fact, no type inference is performed at all in this case.

// type A = string
type A = "ABC" extends Uppercase<infer S> ? S : never;
// type B = never
type B = 123 extends Uppercase<infer S> ? S : never;

This result can be understood as follows. First, even when trying to match "ABC" with Uppercase<infer S>, no inference occurs. Therefore, no information is obtained regarding S. However, since Uppercase is defined in the standard library as type Uppercase<S extends string> = intrinsic;, we know that S has a constraint of extends string. Since there is no further information for S, S is replaced by string. In the case of A, the condition evaluation "ABC" extends Uppercase<string> is performed[1]. Since Uppercase<string> is string, this is the same as "ABC" extends string, which is true. As a result, A contains string, which replaced S. On the other hand, B becomes never because 123 extends Uppercase<string> is false.

To support this, let's try the following experiment. We redefine Uppercase within an arbitrary function scope.

function f() {
    type Uppercase<S> = intrinsic;

    // type A = unknown
    type A = "ABC" extends Uppercase<infer S> ? S : never;
    // type B = unknown
    type B = 123 extends Uppercase<infer S> ? S : never;
}

Unlike the standard library, the definition of Uppercase here does not have the S extends string constraint. Consequently, there is no longer any constraint on S even in Uppercase<infer S>, and as a result, S is inferred as the unknown type.

In this way, even if a type is defined via intrinsic, the parts exposed in the standard library also affect the behavior of Uppercase and other such types. This is quite interesting[2].

Summary

In this article, I explained the mechanism of the intrinsic keyword used to represent types like Uppercase, which is a new feature of TypeScript 4.1.

While the result of Uppercase<T> internally becomes a string mapped type, providing a dedicated syntax for each of them (like uppercase "foo") is undesirable for future extensibility. Thus, the intrinsic keyword mechanism can be seen as a way to hide the existence of string mapped types within the compiler. As a result, the string mapped type has become a special type that has no syntax to represent it directly (it can only be represented indirectly, such as Uppercase<T>). We might see more types like this in the future.

脚注
  1. Strictly speaking, the right side of extends is a "string mapped type for string" and not "the Uppercase type alias applied with a string type argument," but since there is no syntactic notation to represent the former, they are treated as identical here for clarity. ↩︎

  2. The reason for this is that the determination of the constraint for S in Uppercase<infer S> is done syntactically (it syntactically recognizes that infer S is a type argument of Uppercase and looks up the constraint of Uppercase's type argument). Previously, there was a bug where this would fail if enclosed in parentheses like Uppercase<(infer S)>, but I fixed it. ↩︎

GitHubで編集を提案

Discussion