iTranslated by AI

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

How to Beat ChatGPT

に公開
2023/08/03

Introduction

Where ChatGPT Struggles

ChatGPT seems like an all-powerful tool, but it actually has weaknesses.
It doesn't seem to have a very deep understanding of TypeScript's type system, and it often gives repeated incorrect answers when presented with complex problems.
By exploiting this, you can "beat" ChatGPT.
Furthermore, you can even beat the strongest model, GPT-4, using this method.

Problem 1

For example, if you give it the following problem, ChatGPT will answer incorrectly.

https://github.com/type-challenges/type-challenges/tree/main/questions/00529-medium-absolute

Implement an Absolute type that takes a string, number, or bigint and outputs a positive numeric string type.

Example:

type Test = -100;
type Result = Absolute<Test>; // expected to be "100"

Series of Chats

https://chat.openai.com/share/90c62743-a22d-413f-a52f-894ac60fad73

Full chat transcript

User
Implement an Absolute type that takes a string, number, or bigint and outputs a positive numeric string type.

Example

type Test = -100;
type Result = Absolute<Test>; // expected to be "100"

ChatGPT
TypeScript's type system has constraints and cannot directly manipulate strings or numbers. Therefore, type operations that involve manipulating strings or numbers cannot be implemented using the TypeScript type system alone.

However, it is possible to define type behaviors that depend on the value's type. The following code snippet demonstrates this concept:

type Absolute<T extends number | string | bigint> =
  T extends string
  ? `0${T}` extends infer R ? (R extends `${infer _}-${infer P}` ? P : R) : never
  : T extends bigint
  ? T extends -infer U ? U : T
  : T extends -infer U ? U : T;

This Absolute type extends string, number, or bigint. If the type is a string, it performs a process to remove "-" from the string. In the case of number or bigint, it flips the sign if the value is negative.

Note, however, that this is a type-level operation and not an actual value operation. Also, this operation assumes that the string is a numerical representation or that the number is signed.

Finally, the above implementation is only effective when "-" is present and does not include validation for other invalid strings. Further checks would be necessary to handle invalid strings properly.

User
There is an error in this code.
-infer is a syntax error.

ChatGPT
I apologize, that was my mistake. The notation -infer is not valid TypeScript syntax, so attempting to use it for inference will cause an error.

Defining a type that takes the absolute value of a number or bigint is currently impossible in TypeScript's type system. Furthermore, a complete implementation for strings is also extremely difficult.

However, it is possible to take the absolute value when the type is a specific string (i.e., a string representing a negative number). Here is an example:

type Absolute<T extends number | string | bigint> =
    T extends `${infer Sign}-${infer Rest}` ? (Sign extends "" ? T : Rest) : T;

type Test = "-100";
type Result = Absolute<Test>; // expected to be "100"

This allows you to obtain the absolute value of a negative number represented as a string. However, since this method does not work for number or bigint types, it is not practical outside of this limited case.

Finally, the above implementation is only effective when "-" is present and does not include validation for other invalid strings. Further checks would be necessary to handle invalid strings properly.

User
This code returns "-100".
The expected type is "100".

ChatGPT
I apologize, that was my mistake. The type was not applied correctly.

Here is the corrected version. Here, the infer keyword is used to infer the part following the minus sign. Then, that inferred part is used as the resulting type.

type Absolute<T extends number | string | bigint> =
    T extends `-${infer Rest}` ? Rest : T;

type Test = "-100";
type Result = Absolute<Test>; // expected to be "100"

In this corrected version, if the string type starts with "-", it removes that "-". In other words, when it receives the string type "-100", it returns the string type "100".

This corrected code performs the expected behavior correctly. However, this code can only handle string types and cannot directly process number or bigint types.

User
In this code, when a numeric type -100 is passed, it returns the numeric type -100.
As I said at the beginning, it should take string, number, or bigint and output a positive numeric string type.

ChatGPT
I apologize, my explanation was insufficient.

Unfortunately, the TypeScript type system currently cannot perform direct operations on numbers or bigints. Therefore, operations such as receiving a number or bigint and converting it to a string are impossible.

Due to the current constraints of the TypeScript type system, conversion from string, number, or bigint to a string can only be done at runtime. While it's possible to implement a function for this, it's a runtime operation, not a type-level operation.

Here is an example:

function absoluteToString(input: string | number | bigint): string {
    const numberValue = typeof input === "string" ? parseInt(input) : Number(input);
    return Math.abs(numberValue).toString();
}

const test: number = -100;
const result: string = absoluteToString(test); // "100"

This function absoluteToString takes a string, number, or bigint and returns its absolute value as a string. This is a way to bypass the constraints of the TypeScript type system, which cannot directly manipulate numbers or bigints.

However, this function only works at runtime and the output is at the value level rather than the type level, so it cannot be used if you want to perform type-dependent processing. Therefore, the accurate situation is that a solution that fully meets your requirements does not currently exist.

User
It can be implemented at the type level. Here is the answer to this question.

type Absolute<T extends string | number | bigint> = `${T}` extends `-${infer U}`
  ? U
  : T;

ChatGPT
You are exactly right. I apologize for the oversight. Here is the corrected code:

type Absolute<T extends string | number | bigint> = `${T}` extends `-${infer U}`
  ? U
  : `${T}`;

type Test1 = "-100";
type Result1 = Absolute<Test1>; // expected to be "100"

type Test2 = -100;
type Result2 = Absolute<Test2>; // expected to be "100"

In this corrected version, number or bigint is converted to a string type before the operation. This makes it possible to perform operations that would otherwise be direct manipulations of those types.

Thank you for pointing that out.

Problem 2

In addition, ChatGPT also answers incorrectly when given the following problem.

https://github.com/type-challenges/type-challenges/tree/main/questions/00612-medium-kebabcase

Write a KebabCase type that fits the following code:

type FooBarBaz = KebabCase<"FooBarBaz">;
const foobarbaz: FooBarBaz = "foo-bar-baz";

type DoNothing = KebabCase<"do-nothing">;
const doNothing: DoNothing = "do-nothing";

Series of Chats

https://chat.openai.com/share/8625b21d-17de-40c1-a10f-ccb4109ec211

Full chat transcript

User
Write a KebabCase type that fits the following code

type FooBarBaz = KebabCase<"FooBarBaz">;
const foobarbaz: FooBarBaz = "foo-bar-baz";

type DoNothing = KebabCase<"do-nothing">
const doNothing: DoNothing = "do-nothing";

ChatGPT
By defining a "KebabCase" type, you can convert a given CamelCase or PascalCase string into kebab-case. This can be achieved using TypeScript's template literal types and conditional types.

Here is the implementation:

type ToLowerCase<S extends string> =
  S extends `${infer F}${infer R}`
    ? F extends Uppercase<F>
      ? `${Lowercase<F>}${ToLowerCase<R>}`
      : `${F}${ToLowerCase<R>}`
    : S;

type InsertDashBeforeCapital<S extends string> =
  S extends `${infer F}${infer R}`
    ? F extends Uppercase<F>
      ? `-${F}${InsertDashBeforeCapital<R>}`
      : `${F}${InsertDashBeforeCapital<R>}`
    : S;

type KebabCase<S extends string> = ToLowerCase<InsertDashBeforeCapital<S>>;

type FooBarBaz = KebabCase<"FooBarBaz">;
const foobarbaz: FooBarBaz = "foo-bar-baz";

type DoNothing = KebabCase<"do-nothing">
const doNothing: DoNothing = "do-nothing";

In this example, KebabCase converts the given string type S into kebab-case. To do this, it first uses InsertDashBeforeCapital to insert a dash (-) before uppercase letters. Then, it uses ToLowerCase to convert the entire result to lowercase.

This makes KebabCase<"FooBarBaz"> become "foo-bar-baz", and since KebabCase<"do-nothing"> is already in kebab-case, it remains "do-nothing".

User
This code returns -foo-bar-baz and do--nothing.
Please rewrite it.

ChatGPT
I apologize, my previous code does not seem to work correctly when there is an uppercase letter at the beginning of the string or when dashes are consecutive. Here is an improved implementation:

type Dash = '-';

type ToLowerCase<S extends string> =
  S extends `${infer F}${infer R}`
    ? F extends Uppercase<F>
      ? `${Lowercase<F>}${ToLowerCase<R>}`
      : `${F}${ToLowerCase<R>}`
    : S;

type Kebab<S extends string> =
  S extends `${infer T}${infer U}${infer V}`
    ? U extends Uppercase<U>
      ? `${T}${Dash}${U}${V}` extends infer W
        ? Kebab<W>
        : never
      : S
    : S;

type KebabCase<S extends string> = ToLowerCase<Kebab<S>>;

type FooBarBaz = KebabCase<"FooBarBaz">;
const foobarbaz: FooBarBaz = "foo-bar-baz";

type DoNothing = KebabCase<"do-nothing">
const doNothing: DoNothing = "do-nothing";

In this example, the KebabCase type converts the string type S into kebab-case. First, Kebab inserts a dash (-) before uppercase letters, and then ToLowerCase converts the result to all lowercase. This Kebab function is called recursively to insert a dash before all uppercase letters.

User
The following error is output:

Type W does not satisfy the constraint string.
Type '"foo-bar-baz"' cannot be assigned to type '"foobarbaz"'.

ChatGPT
I am very sorry. This problem is due to the limitations of string manipulation in TypeScript, and it is difficult to fully implement the "KebabCase" type in current versions of TypeScript.

TypeScript string manipulation is based on string length or specific patterns, but it cannot handle uppercase and lowercase characters individually. Therefore, an operation to determine if a character is uppercase and add a dash before that character is not currently supported.

As a result, it is common to use JavaScript at runtime to perform operations like "KebabCase". Here is an example:

function kebabCase(str: string): string {
  return str.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2').toLowerCase();
}

const fooBarBaz = kebabCase("FooBarBaz");  // "foo-bar-baz"
const doNothing = kebabCase("do-nothing");  // "do-nothing"

The kebabCase function defined here adds a dash before uppercase letters and then converts all characters to lowercase. This happens at runtime, so the problems caused by TypeScript type constraints do not occur.

However, since this runtime operation cannot be expressed at the type level, it is not possible to accurately define a type like "KebabCase".

User
It can be implemented at the type level. Here is the answer:

type KebabCase<T> = T extends `${infer L}${infer R}`
  ? R extends Uncapitalize<R>
    ? `${Uncapitalize<L>}${KebabCase<R>}`
    : `${Uncapitalize<L>}-${KebabCase<R>}`
  : T;

ChatGPT
Thank you. It was indeed possible to express KebabCase in that way. I apologize for providing incorrect information.

This KebabCase type checks if R starts with an uppercase letter when the string type T is in the form ${infer L}${infer R} (i.e., consisting of two or more characters). If R starts with an uppercase letter (R is not the same as Uncapitalize<R>), it adds a hyphen after L and processes R recursively. If R starts with a lowercase letter, it recursively appends R directly after L. If the string T is a single character, it returns T as is.

I apologize once again for providing incorrect information.

Summary

ChatGPT has its weaknesses, and you can "beat" it by exploiting them.
The problems used as examples are cited from type-challenges.
Well, you probably won't have many occasions to write types like these, but you can enjoy the feeling of superiority by beating ChatGPT.
If you're feeling stressed, please try to beat ChatGPT and bask in that sense of superiority. Become an "Ikirito"!
I am Kirito! (`・ω・´) Kiri

GitHubで編集を提案

Discussion