iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📚
TypeScript-Specialized Cline Programming (Text Version)
This is a version of the content presented at tskaigi (https://tskaigi.mizchi.workers.dev/) modified to be easy to copy and paste.
It is almost identical to the Marp source code, but I am publishing it as is for the purpose of copying and pasting prompts.
Contents of this material
- Prompts that work
- Prompts that don't work and why
- Current understanding
NOTE: Evaluation of Claude 4 released yesterday is not yet complete!!!!
- Claude 4 Opus is scary because it's too expensive
- Feel after using it for a few hours: Showing signs of improvement, but existing issues follow the same trend
Argument: Language-specific prompts are necessary (for now)
- Coding Agents are not optimized for language-specific use cases
- Users need to select and prune best practices
- Technology choices around TS tend to diverge easily
-
Transfer learning between programming languages is unstable
- Even if it memorizes GitHub, whether it can translate and reference correctly based on context is another story
- Performance changes based on the combination of tools
Conclusion first: Tips for writing prompts
- Don't over-write (Skip the "incantation" as much as possible while maintaining reproducibility)
- Illustrate output examples persistently
- Avoid contradictions between co-existing conditions
- Be strict according to the scale of the project
Effective Prompt: Test-Driven Development (Most Important)
Perform TDD. When generating code, always generate the corresponding unit tests.
When making additional code modifications, always confirm that `npm test` passes.
```ts
function add(a: number, b: number) { return a + b }
test("1+2=3", () => {
expect(add(1, 2)).toBe(3);
});
```
- Self-repair capability
- With high-quality tests, the agent can be left to complete the work on its own.
Effective Prompt: Self-Description via Comments
Describe specifications in comments at the beginning of each file.
Output Example
```ts
/**
* Calculates the Euclidean distance between two points
**/
type Point = { x: number; y: number; };
export function distance(a: Point, b: Point): number {
return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2);
}
```
- Maintains consistency in code interpretation during subsequent modifications.
Effective Prompt: In-Source Testing
Write unit tests in the same file as the implementation using Vitest.
Output Example
```ts
export function distance(a: Point, b: Point): number {...}
if (import.meta.vitest) {
const {test, expect} = import.meta.vitest;
test("Calculates the Euclidean distance", () => {
const result = distance({x: 0, y: 0}, {x: 3, y: 4});
expect(distance(result)).toBe(5)
});
}
```
- Comments, implementation, and tests form a "trinity."
- Drawback: Files tend to become bloated (limited to around 800–1,000 lines).
Effective Prompt: Aggregate Domain Types in types.ts
Aggregate domain models within the application in `src/types.ts`.
Describe how the types are used with JSDoc-style comments.
```ts
/**
* Abstract interface for cache
*/
export type AsyncCache<T> = {
get(): Promise<T | void>;
has(): Promise<boolean>;
set(value: T): Promise<void>;
}
```
- Medium scale (1,000+ lines): Use type definitions as the SSoT (Single Source of Truth) across multiple files.
- Reduces
read_filefrequency. Rewriting frequency is relatively low compared to implementation.
Effective Prompt: TS + Functional Domain Modeling
Perform functional domain modeling in TypeScript. Prioritize implementation using functions rather than classes.
Model domains using algebraic data types.
Output Example
````ts
type FetchResult<T, E> = {
ok: true;
data: T
} | {
ok: false;
error: E
}
```
- (Though it is a matter of preference) Immutable data structures are desirable to prevent state divergence.
- Domain Modeling Made Functional: Tackle Software Complexity with Domain-Driven Design and F# | Scott Wlaschin, Kentaro Inomata
Effective Prompt: Specify File Placement Rules
Follow the placement rules for the following monorepo.
script/
<task-name>.ts # Task
packages/
<mod-name>/
examples/
*.ts # Usage examples
src/
index.ts # Entry point
index.test.ts # Unit tests corresponding to files
types.ts # Type definitions
test/
*.test.ts # Integration tests
- Medium scale and above: Reduce the inference cost for agents for each task by making file locations predictable.
Effective Prompt: Split Detailed Instructions into docs/*.md
(System Prompt)
docs/*.md contains necessary documentation for this project.
Refer to them based on user instructions.
(Individual Prompt)
Read @/docs/react-test-pattern.md and add unit tests to @/src/components/Button.tsx.
(docs/react-test-pattern.md)
This document provides instructions on how to write tests for React using @testing-library/react.
Example test code follows...
- For large scale (3,000+ lines)
- Reason: If irrelevant instructions are always present, the model gradually starts to ignore everything.
- Drawback: It's extremely tedious to prepare and keep track of documents.
Copilot TIPS: Temporarily Pin Type Definition Files
- If you "Pin" a file in VS Code's
Open Editors, it will be prioritized as a reference. - This is especially useful for libraries with massive APIs, such as
typescript.d.ts.
Copilot TIPS: Start by Writing Comments
- Write them as if they were inline prompts.
// Function to sort ExecutionResult by priority<TAB>
- Since it looks at the contents of other tabs in Open Editors, it works well with pinning type definitions.
- You will likely end up deleting the comments in the end.
Effective Prompt: Automatic Test Generation Based on Coverage
Aim for 100% test coverage.
Write unit tests in `*.test.ts` for `*.ts`.
For implementations without a .test.ts, add test code by referring to other tests.
1. Run `npx vitest --run --coverage` to get the current coverage.
2. Consider and then add the test code that will increase coverage the most from the current state.
3. Measure the coverage again and confirm that the numbers have improved.
Repeat test generation until the user is satisfied.
-
[2402.09171] Automated Unit Test Improvement using Large Language Models at Meta
- This can be reproduced with Cline without any special effort.
Individual Prompt: Mechanical Migration
Remove lodash by referring to @/docs/You-Dont-Need-Lodash-Underscore.md.
Search for lodash code in the project using grep and replace them.
After replacing, run `npm test` and confirm that tests pass.
- Automate tedious migrations using the LLM's capacity for repetitive tasks.
- Provide a migration guide in advance.
Individual Prompt: Replacing with Libraries with Similar APIs
Replace Library A with Library B.
-
Have the model rewrite code for libraries with similar APIs or concepts.
- Cypress => Playwright
- Jest => Vitest
- Recoil => Jotai
- Vue => Svelte
-
90% can be automated (the rest is pure grit).
-
It is also recommended to prepare a migration guide for this.
Effective: Ability to Read URLs (MCP)
(System Prompt)
When given a URL, you can retrieve the content of that URL in Markdown using the following command:
`npx -y @mizchi/readability --format=md <url>`
(Individual Prompt: 1)
Read https://blog.cloudflare.com/cloudflare-containers-coming-2025/
(Individual Prompt: 2)
Summarize the content you just read and save it under docs/.
-
https://github.com/mizchi/readability is a CLI for content extraction and Markdown conversion.
- Instructing the model to read linked pages results in behavior similar to "Deep Research."
-
@mizchi/npm-summary - JSR
- Generates use cases based on
.d.tsvia$ npm-summary zod@latest.
- Generates use cases based on
Analysis of Prompts that Don't Work
Not Working: Designing with Types Alone
In Architect mode, first organize specifications by type signatures and their use cases.
Propose types and test code using them to the user, and implement only after approval.
Output Example
```ts
declare function add(a: number, b: number): number;
test("add(1,2) => 3", () => {
expect(1, 2).toBe(3);
})
```
- Almost certainly ignored. Models lack the ability to design abstractly using only types.
- "Fix only the implementation while keeping tests and types as they are" also tends to be ignored.
Not Working: Poor at Async Exception Handling
async function main() {
try {
await init();
try {
await run();
} catch (err) {
/// ...
}
} catch (err) {
console.error(err)
}
}
- Tends to mindlessly swallow errors with try-catch (notable in Gemini).
- One of the factors causing failures in large-scale projects.
Not Working: Poor at Environment Setup
(User)
Set up with typescript + vite + vitest
(Assistant)
foo.ts cannot be executed.
Installing vite-node. Installing ts-node, installing tsx. Let's try deleting tsconfig.json.
Changing all extensions to .cjs, removing `type: module` from package.json.
- The "environment" itself is the most powerful prompt; zero-shot setup diverges.
- Cline: Excessive steps turn into a disadvantage, leading to environment destruction.
- Vibe Coding: Selection of boilerplates is crucial.
Not Working: Module Interfaces Diverge
Reduce exports to make it easier for module users to use.
```ts
export {
generateDetailedComplexityReport,
generateMetricsReport,
generateModuleComplexityReport,
} from "./core/mod.ts";
```
- Reality: Exports everything as soon as it's implemented
- Contracts between modules bloat and break down.
- Tentative solution: Use tsr for dead code detection equivalent to TreeShaking.
npx -y tsr src/index.ts test/**/*.ts
Not Working: It's bad that it's "there"!
-
Chekhov's Gun Law (LLM Prompt Engineering)
-
If in the first act you have hung a pistol on the wall, then in the following one it should be fired. Otherwise, don't put it there.
- Even if it loads irrelevant resources, it persists in trying to use them.
-
- For large-scale code + Cline, the mere fact that something is found via
lsorgrepbecomes noise.
Not Working: Consuming Too Many Debug Logs
console.log("debug: start process")
for (const item of items) {
console.log("debug: process item", item);
// ...
}
console.log("debug: end process")
- Consumes the context window with print debugging it generated itself.
- Leaves scattered debug code behind (notably in the Claude 3.x series).
Conclusion: LLMs are Still Poor at Coding
-
Self-destruction due to design failure with low-quality code
- Lack of refactoring guidelines
- Low ability to identify unnecessary code
- Inability to design APIs from a modular perspective
-
Reverting to original low-quality code even after user refactoring
- The model seems to believe the code it wrote is the best.
- A truly terrible experience.
Current Understanding
TypeScript + LLM: Pros
- A vast amount of public code on GitHub results in an incomparably large training volume.
-
A "peaky" type system that prioritizes expressiveness over safety
- Makes it easier to model types that correspond to natural language.
- Pseudo-algebraic data types can be realized using tagged unions.
-
Abundant static analysis tools and a large user base
- tsc / eslint / babel / ts-morph / oxc / biome ...
- The peace of mind that someone will have a solution if you run into trouble.
TypeScript Language Specification Issues
- Weak exception handling mechanisms induce sloppy try-catch blocks.
- Mutable by default &
readonlyis cumbersome to use. - Insufficient module access control.
// Code with unclear processes
import { unsafeFunc } from "../../external/module/internal";
export async function main(input: any): Promise<void> {
let v = input;
try {
v = await unsafeFunc(input, () => new Error("something fallback"));
} catch (err) {
if (err instanceof Error) {}
}
}
(I want an effect system...)
My Current Practices
-
Generating code for PoC/prototypes
- Aim for within 800 lines in a single file.
-
Integrating while refactoring by myself
- Especially for interface design, I do it myself.
-
Reflecting failure patterns back into prompts
- Like tending to a bonsai.
-
Documenting successful patterns
- Building
docs/*.mdfor future reference.
- Building
Deno: Probably the Best "Vibe Coding" Environment Right Now
import fs from "node:fs";
import { ok } from 'npm:neverthrow@8.2.0';
import { expect } from "jsr:@std/expect";
Deno.test("test", () => {
exect(1).toBe(1);
});
- Control execution permissions with Deno Permissions.
- Example:
$ deno run --deny-net --deny-env --allow-read=./tmp run.ts - Essential considering future training data contamination.
- Example:
- No pre-installation of libraries required + Node.js compatibility layer.
Deno PoC: Prompts
- Implement as a standalone file in Deno's Node.js compatibility mode.
- Describe specifications in comments at the top of the file.
- Write tests in the same file as the implementation using `Deno.test()`.
- Provide a usage sample within `if(import.meta.main) {}`. You may perform debugging here.
- Use function-oriented domain modeling. Prioritize implementation with functions over classes.
Output Example
```ts
/**
* <Specifications of this module>
**/
import fs from "node:fs";
import { ok } from 'npm:neverthrow@8.2.0';
export function add(a: number, b: number): number {
return a + b;
}
if (import.meta.main) {
console.log(add(3, 4));
}
import { expect } from "@std/expect";
Deno.test("Should return the result of addition", () => {
expect(add(1, 2)).toBe(3);
})
```
Countermeasure: Converting Prompts to Rule-Based via Linting
- Example: Custom rule
do-try - https://github.com/mizchi/deno-lint-plugin-do-try
// Functions starting with 'do' require try-catch
try {
const v = await doGetData();
} catch (_err) {}
// Exception neutrality: only functions starting with 'do' are exempt from try-catch
async function doMain() {
await doXXX();
await doYYY();
}
Vibe Coding Lint Rules
$ deno init
I want to implement a Deno lint rule by referring to the following URL:
`https://docs.deno.com/runtime/reference/lint_plugins/`
Implement a rule that satisfies the following conditions:
```ts
// Case that causes an error
const v = await doGetData();
// Case that is allowed
try {
const v = await doGetData();
} catch (_err) {}
```
Summary: What has changed with Agentic Coding?
Transformation of Programming Itself
-
Skills that have become more important
- Speed up development with Test-Driven Development
-
Newly emerging areas
- Techniques for predicting the strengths and developmental stages of LLMs
- Prompt Engineering
-
Things that haven't changed
- The ultimate difficulty and complexity of programming
- It has undoubtedly become easier to learn through Natural Language to Code
Summary | Conclusion
-
Current tradeoff between cost and performance
- Entrust it with what it's good at for now
- Humans handle tasks that AI is poor at (keeping automation costs in mind). Keep an eye on VLM costs
-
To survive as an engineer, shift skills toward code generation
- The rewards of successful automation are disruptive, far beyond 10x
- High cost-performance in automated testing + prompt engineering
The end
Discussion