惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

H
Help Net Security
S
Secure Thoughts
I
Intezer
Project Zero
Project Zero
Stack Overflow Blog
Stack Overflow Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
F
Full Disclosure
P
Proofpoint News Feed
T
The Exploit Database - CXSecurity.com
人人都是产品经理
人人都是产品经理
博客园_首页
J
Java Code Geeks
Recorded Future
Recorded Future
K
Kaspersky official blog
GbyAI
GbyAI
S
Schneier on Security
The Cloudflare Blog
Spread Privacy
Spread Privacy
C
Cisco Blogs
The Hacker News
The Hacker News
博客园 - 三生石上(FineUI控件)
H
Hackread – Cybersecurity News, Data Breaches, AI and More
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
爱范儿
爱范儿
Microsoft Azure Blog
Microsoft Azure Blog
Know Your Adversary
Know Your Adversary
T
Tenable Blog
A
Arctic Wolf
Blog — PlanetScale
Blog — PlanetScale
H
Hacker News: Front Page
The Last Watchdog
The Last Watchdog
O
OpenAI News
Last Week in AI
Last Week in AI
B
Blog RSS Feed
T
Troy Hunt's Blog
G
GRAHAM CLULEY
N
Netflix TechBlog - Medium
Vercel News
Vercel News
量子位
The Register - Security
The Register - Security
Google Online Security Blog
Google Online Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
C
CERT Recently Published Vulnerability Notes
Cisco Talos Blog
Cisco Talos Blog
U
Unit 42
Security Archives - TechRepublic
Security Archives - TechRepublic
C
Cyber Attacks, Cyber Crime and Cyber Security
N
News and Events Feed by Topic

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building a Rock-Paper-Scissors CLI with TypeScript — Union Types, Conditionals, and Jest
Uya · 2026-05-25 · via DEV Community

Uya

Uya

Posted on • Originally published at zenn.dev

Introduction

This is my second article as a Java engineer learning TypeScript from scratch.

In my first article, I built a BMI Calculator CLI and learned about union types, function separation, and Vitest. This time, I built a Rock-Paper-Scissors game (CLI) and focused on:

  • Expressing game "hands" and "results" with union types
  • Understanding when to use if vs else if
  • Writing unit tests with Jest + ts-jest (I used Vitest last time — this time I wrestled with Jest)
  • Understanding the difference between the nullish coalescing operator ?? and type assertion as

Same as before — I write honestly about what I struggled with, what I figured out, and what I asked AI to help with.


My Learning Style (AI Transparency)

I use Claude Pro (for design discussions and Q&A) and Cursor Pro (for coding support) as learning companions.

However, I follow these rules for myself:

  • I write all the code myself — I never ask AI to write code for me
  • AI helps with hints, spec clarification, and bug spotting
  • I make sure I understand why something works before moving on

In this article, I clearly separate "what I implemented myself" from "what I asked AI for."


What I Built

A CLI Rock-Paper-Scissors game where you play against the computer.

$ npm start

Enter your hand (rock, paper, scissors): rock
Player: rock
Computer: scissors
Result: win

Invalid input (anything other than rock, paper, or scissors) is rejected with a validation message.

📦 Repository: https://github.com/uya0526-design/janken-game


Project Structure

janken-game/
├── src/
│   ├── index.ts           # Entry point / CLI I/O
│   ├── game.ts            # Game logic (result determination, CPU hand generation)
│   ├── types.ts           # Type definitions
│   └── __tests__/
│       └── game.test.ts   # Unit tests (all 9 combinations)
├── jest.config.js
├── package.json
└── tsconfig.json

Same as my BMI project — responsibilities are separated by file.


Tech Stack

  • TypeScript
  • Node.js (readline module)
  • Jest + ts-jest (unit testing)

What I Implemented Myself

types.ts — Type Definitions

export type Hand   = 'rock' | 'paper' | 'scissors';
export type Result = 'win'  | 'lose'  | 'draw';

I chose this design myself, based on experience from the previous project.

Why union types instead of enum?
With enum, the underlying values are numbers (0, 1, 2), which makes logs harder to read. With union types, the string values appear as-is — cleaner for debugging and more idiomatic TypeScript.

I also added export myself, knowing these types would be needed in other files.


game.ts — determineResult function

All 9 combinations (3×3) of win/lose/draw logic live here.

import type { Hand, Result } from './types.js';

export function determineResult(player: Hand, computer: Hand): Result {
  if (player === computer) return 'draw';
  if (
    (player === 'rock'     && computer === 'scissors') ||
    (player === 'scissors' && computer === 'paper')    ||
    (player === 'paper'    && computer === 'rock')
  ) {
    return 'win';
  }
  return 'lose';
}

if vs else if — where I got it wrong first:

My initial version looked like this:

// First attempt (not ideal)
if (player === computer) return 'draw';
if (player === 'rock' && computer === 'scissors') return 'win';
if (player === 'rock' && computer === 'paper') return 'lose';
// ... all 9 combinations as separate if statements

This works because of the return statements, but the intent is unclear — after matching 'draw', the other if blocks still get evaluated. AI pointed out that mutually exclusive conditions should use else if to signal that only one branch can be true. That feedback led me to the cleaner version above.


game.ts — getComputerHand function

export function getComputerHand(): Hand {
  const hands: Hand[] = ['rock', 'paper', 'scissors'];
  const index = Math.floor(Math.random() * hands.length);
  return hands[index] as Hand;
}

Design decisions:

  • Used hands.length instead of hardcoding * 3
  • Chose as Hand over ?? 'rock' after understanding the difference

The nullish coalescing operator ?? returns the right-hand side only when the left is null or undefined. Since hands[index] is always a valid Hand value within bounds, a fallback isn't needed. I used as Hand instead to explicitly tell the compiler "this is safe, I've validated it."


index.ts — CLI Input/Output

import * as readline from 'readline';
import { determineResult, getComputerHand } from './game.js';
import type { Hand } from './types.js';

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const validHands: Hand[] = ['rock', 'paper', 'scissors'];

rl.question('Enter your hand (rock, paper, scissors): ', (input) => {
  if (!validHands.includes(input as Hand)) {
    console.log('Invalid input. Please enter rock, paper, or scissors.');
    rl.close();
    return;
  }

  const playerHand = input as Hand;
  const computerHand = getComputerHand();
  const result = determineResult(playerHand, computerHand);

  console.log(`Player: ${playerHand}`);
  console.log(`Computer: ${computerHand}`);
  console.log(`Result: ${result}`);

  rl.close();
});

One lesson from the previous project: always call rl.close() in every exit path. This time I made sure both the validation failure path and the happy path close properly.


game.test.ts — Unit Tests with Jest

The goal: cover all 9 combinations (3 wins + 3 losses + 3 draws).

import { determineResult } from '../game';

describe('determineResult', () => {
  // Win (3 patterns)
  test('rock beats scissors', () => {
    expect(determineResult('rock', 'scissors')).toBe('win');
  });
  test('scissors beats paper', () => {
    expect(determineResult('scissors', 'paper')).toBe('win');
  });
  test('paper beats rock', () => {
    expect(determineResult('paper', 'rock')).toBe('win');
  });

  // Lose (3 patterns)
  test('rock loses to paper', () => {
    expect(determineResult('rock', 'paper')).toBe('lose');
  });
  test('scissors loses to rock', () => {
    expect(determineResult('scissors', 'rock')).toBe('lose');
  });
  test('paper loses to scissors', () => {
    expect(determineResult('paper', 'scissors')).toBe('lose');
  });

  // Draw (3 patterns)
  test('rock vs rock is a draw', () => {
    expect(determineResult('rock', 'rock')).toBe('draw');
  });
  test('scissors vs scissors is a draw', () => {
    expect(determineResult('scissors', 'scissors')).toBe('draw');
  });
  test('paper vs paper is a draw', () => {
    expect(determineResult('paper', 'paper')).toBe('draw');
  });
});

Test results:

 PASS  src/__tests__/game.test.ts
  determineResult
    ✓ rock beats scissors
    ✓ scissors beats paper
    ✓ paper beats rock
    ✓ rock loses to paper
    ✓ scissors loses to rock
    ✓ paper loses to scissors
    ✓ rock vs rock is a draw
    ✓ scissors vs scissors is a draw
    ✓ paper vs paper is a draw

Tests: 9 passed, 9 total

The boundary value mindset I developed in the BMI project carried over here — for Rock-Paper-Scissors, full coverage means all 9 combinations.


What I Asked AI For

Topic What AI helped with
Hand type design Introduced me to union types and string literal types
if vs else if Pointed out that mutually exclusive conditions should use else if
CPU random hand Suggested the Math.random() + array approach and flagged the need for type assertion
Missing rl.close() Spotted that the happy path was missing rl.close()
Jest basics Showed me the describe / test / expect structure

Where I Got Stuck

1. Jest TypeScript error: TS5107: moduleResolution=node10 deprecated

Situation: Running npm test gave this error:

error TS5107: Option 'moduleResolution' value 'node10' is deprecated.

Investigation: I read the error message and figured out that tsconfig.json was using an outdated setting.

Fix: Updated module and moduleResolution in tsconfig.json to nodenext:

{
  "compilerOptions": {
    "module": "nodenext",
    "moduleResolution": "nodenext"
  }
}

Important caveat: I kept "type": "commonjs" in package.json. Changing it to "module" caused Jest compatibility errors. These two settings are independent — tsconfig.json controls the TypeScript compiler, while package.json controls how Node.js handles .js files at runtime. The right combination depends on the tooling version.


2. Three losses in a row — is Math.random broken?

Situation: After losing 3 times in a row out of 5 games, I started to wonder if the CPU hand wasn't actually random.

Investigation: I re-read the code — the implementation was correct.

Insight: With only 5 samples, variance is completely expected (law of large numbers). Over 100 games the distribution would even out. This wasn't a bug — it was a statistics lesson.


3. .js extension required with moduleResolution: nodenext

Situation: Importing from types.ts threw this error:

Cannot find module './types'

Fix: With moduleResolution: nodenext, TypeScript requires .js extensions even in .ts files:

// ❌ Does not work
import type { Hand, Result } from './types';

// ✅ Works
import type { Hand, Result } from './types.js';

The reason: TypeScript assumes you're referencing the compiled output (.js), not the source file (.ts). It felt strange at first, but once I understood the reasoning it made sense.


What I Learned

TypeScript Type System

Topic Key Takeaway
Union types Define a fixed set of allowed values as a type (e.g. Hand limited to rock, paper, or scissors)
String literal types The string itself becomes the type. Lighter than enum and more idiomatic TypeScript
Type assertion as Tells the compiler "trust me, I've validated this" — use only after validation
import type Imports type information only — not included in the runtime bundle

Conditional Logic

Topic Key Takeaway
if vs else if Mutually exclusive conditions should use else if to make intent clear
Early return Returning early on invalid input keeps nesting shallow and logic readable

Nullish Coalescing ??

Returns the right-hand side only when the left is null or undefined. Unlike ||, it does not trigger on 0 or "". Useful for fallback values when undefined is the only concern — but not needed when array bounds are guaranteed.

Jest Unit Testing

Topic Key Takeaway
describe Groups related tests (similar to @Nested in JUnit)
test Defines an individual test case (similar to @Test in JUnit)
expect(...).toBe(...) Strict equality check
Full coverage mindset Rock-Paper-Scissors has 3×3 = 9 combinations — covering all of them gives confidence in the logic

Module System Configuration

A deeper understanding than the previous project:

  • tsconfig.json (module / moduleResolution) — controls the TypeScript compiler
  • package.json ("type") — controls how Node.js interprets .js files at runtime
  • These are independent settings; the right combination depends on your toolchain

Reflection

Where my Java background helped: I naturally structured the logic before writing code (design-first thinking). Writing all 9 test cases proactively also reflects a quality-first mindset from Java development.

Where I got tripped up: The module resolution configuration (tsconfig.json vs package.json) has no real equivalent in Java. I was confused at first, but reading the error messages carefully led me to the fix — which felt like a real debugging win.

The "is this a bug?" moment: Suspecting Math.random after 3 losses taught me not to draw conclusions from small samples. That's a useful development instinct to build early.


Wrapping Up

This was my second TypeScript project — a Rock-Paper-Scissors CLI.

Progress since the BMI calculator:

  1. Chose union types on my own, without being prompted
  2. Understood else if and used it to express intent clearly
  3. Designed and implemented all 9 test combinations myself
  4. Read an error message, investigated, and fixed it independently

The full learning log is in LEARNING_LOG.md.


This article is part of my public learning journey using AI tools (Claude Pro / Cursor Pro). All code is written by me — AI is used for design discussions, bug hints, and spec clarification only.