← 返回题库总览

编程入门实操

TypeScript 入门 · 代码审查训练

30 道四选一 · 阅读代码,辨认问题,选择修复 · 原创练习

按 strict 模式审查;第 28–29 题注明额外配置。示例只展示,不会执行。

已答 0/30正确 0错误 0正确率 —
Question 1单选TypeScript · Code review

The price must be a number used in calculations. Which review comment fixes this declaration?

price 要作为数字参与计算。哪条审查意见能修复这个声明?

price は計算に使う数値。どのレビュー指摘で宣言を修正できるか。

const price: number = "19";
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 C

Quoted "19" is a string, not a number. Type annotations check values; they do not convert them. Use 19 for a numeric price, or explicitly parse and validate external text before assigning it.

带引号的 "19" 是字符串。类型标注负责检查,不负责转换。数字价格应写成 19;若数据来自外部文本,应先明确解析并验证,再赋给数字变量。

"19" は文字列。型注釈は検査であり変換ではない。数値の価格なら 19 と書く。外部テキストなら明示的に解析・検証してから代入する。

TypeScript Handbook

Question 2单选TypeScript · Code review

enabled should remain a boolean flag. What is the appropriate correction?

enabled 应始终是布尔开关。正确的修复是什么?

enabled を真偽値のフラグとして保ちたい。適切な修正はどれか。

let enabled = true;
enabled = "false";
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 A

Type inference gives enabled the boolean type. The string "false" is neither the boolean false nor a valid boolean assignment. It is also truthy at runtime, so using text can reverse an intended condition.

类型推断使 enabled 成为 boolean。字符串 "false" 不等于布尔值 false,也不能赋给 boolean。它在运行时还是 truthy,用文本代替布尔值可能使条件判断出现反效果。

enabled は boolean と推論される。文字列 "false" は真偽値 false ではなく、boolean に代入できない。実行時には truthy なので条件の意図も崩れる。

TypeScript Handbook

Question 3单选TypeScript · Code review

This array must contain only numbers. Which change keeps that contract?

数组应只包含数字。哪项修改能保持这个约定?

数値だけを入れる配列。どの変更が型の契約を守るか。

const scores: number[] = [70, 80];
scores.push("90");
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 D

number[] constrains each element to number, including later push calls. const prevents rebinding the array variable; it does not freeze the array or permit incompatible element types.

number[] 限制每个元素都为 number,后续 push 也必须遵守。const 禁止变量重新指向另一个数组,但不会冻结数组,更不会放宽元素类型。

number[] は後から push する要素にも number を要求する。const は変数の再代入を禁じるだけで、配列を凍結したり要素の型を緩めたりはしない。

TypeScript Handbook

Question 4单选TypeScript · Code review

The tuple stores a person's name followed by their age. Which review comment is correct?

元组用于按顺序保存姓名、年龄。哪条审查意见正确?

名前、年齢の順で格納するタプル。正しい指摘はどれか。

const person: [string, number] = [20, "Kai"];
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 B

A tuple describes types by position: index 0 must be string and index 1 number. A union array such as (string | number)[] would not express this fixed name-then-age contract.

元组按位置约束类型:第 0 项必须是 string,第 1 项必须是 number。(string | number)[] 只约束元素属于两种类型之一,不能表达固定的“姓名在前、年龄在后”。

タプルは位置ごとに型を決める。0番目は string、1番目は number。(string | number)[] では名前と年齢の固定順序までは表せない。

TypeScript Handbook

Question 5单选TypeScript · Code review

With strict checking enabled, this numeric function has an implicit-any parameter. What should the reviewer request?

开启严格检查后,这个数字处理函数的参数出现隐式 any。应要求怎样修复?

strict 有効時、数値処理関数の引数が暗黙の any になる。何を修正すべきか。

function double(value) {
  return value * 2;
}
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 A

Arithmetic in the body does not supply a declared parameter type for this standalone function. value: number documents and checks callers. A return annotation alone does not remove the parameter's implicit any.

对于这个独立函数,函数体里的乘法不会替参数声明类型。value: number 能约束调用者并说明约定;仅标注返回类型不能消除参数的隐式 any。

独立した関数では、本体の掛け算から引数型は宣言されない。value: number で呼び出しを検査する。戻り値だけの注釈では引数の暗黙の any は解消しない。

TypeScript Handbook

Question 6单选TypeScript · Code review

total must return a numeric total, not formatted text. Which fix preserves that promise?

total 应返回数字总额,而非格式化文本。哪项修复符合这个约定?

total は表示用文字列ではなく数値の合計を返す。契約を守る修正はどれか。

function total(): number {
  return "30";
}
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 C

The declared number return type requires a number on this return path. Return 30 for a numeric total; convert to display text separately. Changing the contract to string would not satisfy the stated requirement.

声明返回 number 后,这条返回路径必须提供数字。应返回 30,显示格式化另行处理。把返回类型改成 string 虽可能通过检查,却不符合题目要求的数字总额。

number の戻り値には数値が必要。合計は 30 として返し、表示用変換は別に行う。型を string に変えるだけでは数値を返す要件を満たさない。

TypeScript Handbook

Question 7单选TypeScript · Code review

greet expects a person's name as text. Which call is appropriate?

greet 接收文本形式的姓名。正确的调用应是什么?

greet は文字列の名前を受け取る。適切な呼び出しはどれか。

function greet(name: string) {
  return name.toUpperCase();
}
greet(7);
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 B

The argument must match string. The annotation neither makes name optional nor adds a runtime conversion. A real text name such as "Kai" respects the function contract without weakening its parameter type.

实参必须符合 string。类型标注不会把 name 变成可选参数,也不会添加运行时转换。传入 "Kai" 这样的文本姓名即可,无需放宽参数类型。

引数は string に合う必要がある。型注釈で省略可能になったり実行時変換が追加されたりはしない。"Kai" のような名前を渡せばよい。

TypeScript Handbook

Question 8单选TypeScript · Code review

Every User must have an id and a name. What is missing from this object literal?

每个 User 都必须有 id 和 name。这个对象字面量缺少什么?

User には id と name が必須。このオブジェクトリテラルには何が足りないか。

type User = { id: number; name: string };
const user: User = { name: "Kai" };
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 D

Both properties are required because neither has a ? marker. Add a numeric id rather than making a required business field optional merely to silence the compiler. A type alias does not create missing runtime properties.

两个属性都没有 ?,因此都必填。应补上数字 id,而不是为消除报错就把业务必填字段改成可选。类型别名也不会在运行时自动补齐属性。

? がないため両方とも必須。エラーを消すだけの目的で必須項目を任意にせず、数値の id を追加する。型エイリアスが実行時に属性を補うことはない。

TypeScript Handbook

Question 9单选TypeScript · Code review

A missing nickname should display as an empty string. What safe fix handles the optional property?

没有昵称时应显示空字符串。如何安全处理这个可选属性?

ニックネームがなければ空文字を表示したい。任意プロパティを安全に扱う修正はどれか。

function label(user: { nickname?: string }): string {
  return user.nickname.toUpperCase();
}
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 C

Reading nickname may produce undefined. Optional chaining skips the method call in that case, and ?? supplies the required empty string. A non-null assertion only suppresses a check; it does not add a value or a runtime guard.

读取 nickname 时可能得到 undefined。可选链会在此时跳过方法调用,再由 ?? 补上要求的空字符串。非空断言只影响类型检查,不会添加值或运行时保护。

nickname は undefined の可能性がある。?. で呼び出しを避け、?? で空文字を補う。非 null アサーションは検査を抑えるだけで値や実行時ガードを追加しない。

TypeScript Handbook

Question 10单选TypeScript · Code review

The function accepts a number or a string and must format both. Which review comment is correct?

函数接收数字或字符串,并且都要支持格式化。哪条审查意见正确?

数値と文字列の両方を整形したい。正しいレビュー指摘はどれか。

function format(value: string | number): string {
  return value.toUpperCase();
}
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 B

A union permits only operations safe for every possible member until narrowed. typeof is a runtime check that narrows the string branch. Numbers need their own handling, such as String(value), rather than an unsafe assertion.

联合类型在被缩窄前,只允许对所有可能成员都安全的操作。typeof 是运行时判断,可把字符串分支缩窄为 string;数字分支应单独处理,例如 String(value),而不是强行断言。

ユニオンは絞り込み前には全メンバーに安全な操作しか許さない。typeof で文字列の分岐を絞り込み、数値側は String(value) などで処理する。危険な型アサーションは不要。

TypeScript Handbook

Question 11单选TypeScript · Code review

The heading might not exist. Which review comment prevents a null dereference?

页面上可能不存在这个标题。哪项修改可防止访问 null?

見出しが存在しない場合もある。null へのアクセスを防ぐ修正はどれか。

const heading = document.querySelector("h1");
heading.textContent = "Ready";
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 D

querySelector returns an element or null. A real null check narrows the type and protects the runtime operation. Adding ! would remove a compiler warning but would not create a missing heading.

querySelector 返回元素或 null。实际的空值检查既能缩窄类型,也能保护运行时操作。添加 ! 只会消除类型报错,不会让缺失的标题凭空出现。

querySelector は要素か null を返す。実際に null を確認すれば型も絞られ、実行時にも安全になる。! を付けても存在しない見出しは作られない。

TypeScript Handbook

Question 12单选TypeScript · Code review

The input is untrusted and may be any type. Which correction safely trims strings and rejects other values?

输入不可信,可能是任意类型。如何安全地裁掉字符串首尾空白,并拒绝其他类型?

信頼できない入力の型は不明。文字列だけを trim し、それ以外を拒否する修正はどれか。

function normalize(value: unknown): string {
  return value.trim();
}
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 A

unknown requires narrowing before property or method access. A typeof guard performs an actual runtime check. Neither any nor a type assertion validates data arriving from users, JSON or an API.

unknown 必须先缩窄才能访问属性或方法。typeof 判断会真正检查运行时类型;any 和类型断言都不会验证用户输入、JSON 或 API 数据。

unknown の属性やメソッドを使う前に型を絞り込む。typeof は実行時にも検査する。any や型アサーションはユーザー入力、JSON、APIの値を検証しない。

TypeScript Handbook

Question 13单选TypeScript · Code review

Only left and right are supported directions. Which correction respects the allowed values?

系统只支持 left 和 right 两个方向。哪项修复符合允许值约定?

方向は left と right のみ。許可された値を守る修正はどれか。

type Direction = "left" | "right";
const direction: Direction = "up";
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 C

A string-literal union is a finite set of exact values. "up" is outside that set. Do not widen the type to string merely to accept an input the application does not support.

字符串字面量联合表示一组精确的允许值,"up" 不在其中。不要为了接受系统不支持的输入,就简单把类型放宽成 string。

文字列リテラルのユニオンは値を厳密に限定する。"up" は範囲外。未対応の入力を通すだけのために string へ広げない。

TypeScript Handbook

Question 14单选TypeScript · Code review

The id is intentionally readonly. How should code represent a copy with a different id without mutating the original?

id 有意设为只读。如何得到不同 id 的副本,同时不修改原对象?

id は意図的に読み取り専用。元のオブジェクトを変更せず別の id のコピーを作るにはどうするか。

type User = { readonly id: number; name: string };
const user: User = { id: 1, name: "Kai" };
user.id = 2;
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 D

readonly forbids assigning to id through this typed reference after creation. Object spread builds a new object with its own initial id. const and readonly address different things; neither is a general deep runtime freeze.

readonly 禁止在创建后通过这个类型引用重新赋值 id。对象展开会创建新对象,可为其设置初始 id。const 和 readonly 约束的对象不同,也都不等于通用的运行时深冻结。

readonly は作成後、この型の参照から id に再代入することを禁じる。スプレッドなら別のオブジェクトの初期値として id を設定できる。const も readonly も汎用の実行時ディープフリーズではない。

TypeScript Handbook

Question 15单选TypeScript · Code review

Do not mutate the readonly input list. Which change creates a new list containing "new"?

不要修改只读输入数组。哪项修改会创建一个包含 "new" 的新数组?

読み取り専用の入力配列は変更しない。"new" を含む新しい配列を作る修正はどれか。

function append(items: readonly string[]) {
  items.push("new");
  return items;
}
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 A

readonly string[] exposes read operations but not mutation methods such as push. Spread reads the input into a new array, then adds the new element. It preserves the input contract without casting away readonly.

readonly string[] 提供读取操作,但没有 push 这样的修改方法。展开语法把输入读入新数组,再加入新元素,无需通过断言绕过只读约定。

readonly string[] では push などの変更操作は使えない。スプレッドで新しい配列へ読み出し、要素を追加する。readonly をアサーションで消す必要はない。

TypeScript Handbook

Question 16单选TypeScript · Code review

identity should return the same value and type it receives. Which change repairs its generic contract?

identity 应返回传入的原值,并保留其类型。哪项修改能修复泛型约定?

identity は受け取った値と型をそのまま返す。ジェネリックの契約を直す変更はどれか。

function identity<T>(value: T): T {
  return "fixed";
}
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 B

T can be number, an object or another type, so a fixed string cannot satisfy every T. Returning value preserves the relationship between input and output. Generics describe that relationship rather than converting data.

T 可能是 number、对象或其他类型,因此固定字符串不可能满足所有 T。返回 value 才能保留输入输出的类型关系。泛型用于描述关系,不会自动转换数据。

T は number やオブジェクトなどにもなるため、固定文字列を常に T として返せない。value を返せば入力と出力の型の関係が保たれる。ジェネリックは変換機能ではない。

TypeScript Handbook

Question 17单选TypeScript · Code review

key must be a key actually declared on User. Which assignment is valid?

key 必须是 User 实际声明的键。哪项赋值有效?

key は User で宣言したキーに限定する。有効な代入はどれか。

type User = { name: string; age: number };
const key: keyof User = "email";
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 A

For this type, keyof User is "name" | "age". It refers to property names, not their value types or values. It does not change the runtime object or invent an email field.

这里 keyof User 为 "name" | "age",表示属性名,而非属性值或属性值的类型。它不会修改运行时对象,也不会创造 email 字段。

この keyof User は "name" | "age"。属性名を表し、属性の値や値の型ではない。実行時のオブジェクトを変更したり email を作ったりはしない。

TypeScript Handbook

Question 18单选TypeScript · Code review

The greeting table requires both English and Japanese entries. What is the correct review finding?

问候表必须同时提供英语和日语条目。正确的审查结论是什么?

挨拶の表には英語と日本語の両方が必須。正しい指摘はどれか。

type Locale = "en" | "ja";
const greetings: Record<Locale, string> = { en: "Hello" };
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 D

Record<Locale, string> requires every key in Locale, each mapping to a string. A union in the key position does not mean that one key may be omitted. Types do not generate translations at runtime.

Record<Locale, string> 要求 Locale 中每个键都存在,且值为字符串。键类型中的联合不表示允许缺少其中一个键,类型也不会在运行时生成翻译。

Record<Locale, string> は Locale の全キーに文字列の値を要求する。キーのユニオンは一方を省略できるという意味ではない。型が実行時に翻訳を作ることもない。

TypeScript Handbook

Question 19单选TypeScript · Code review

An update may omit theme. If omitted, the label should use LIGHT. Which change is safe?

更新对象可能省略 theme。省略时标签应使用 LIGHT。哪项修复安全?

更新では theme が省略されることもある。その場合は LIGHT を使う。安全な修正はどれか。

type Settings = { theme: string };
function themeLabel(update: Partial<Settings>): string {
  return update.theme.toUpperCase();
}
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 B

Partial makes every property optional; reading theme can therefore yield undefined. Apply the default before calling a string method. Changing the parameter to Required would reject the intentionally supported empty update.

Partial 会把所有属性变成可选,因此读取 theme 可能得到 undefined。应先提供默认值,再调用字符串方法。把参数改成 Required 会拒绝原本允许的空更新对象。

Partial は全属性を任意にするので theme は undefined の可能性がある。文字列メソッドの前に既定値を補う。Required にすると、許容したい空の更新を拒否してしまう。

TypeScript Handbook

Question 20单选TypeScript · Code review

This object literal must contain only the id field selected by PublicUser. What should be changed?

这个对象字面量应只包含 PublicUser 选取的 id 字段。应该修改什么?

このオブジェクトリテラルには PublicUser が選んだ id だけを含めたい。何を変更すべきか。

type User = { id: number; name: string };
type PublicUser = Pick<User, "id">;
const user: PublicUser = { id: 1, name: "Kai" };
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 C

Pick<User, "id"> describes only id, so this fresh literal gets an excess-property error for name. Remove the field here. Pick is a compile-time type operation, not a runtime filter that strips fields from existing objects.

Pick<User, "id"> 只描述 id,因此这个新对象字面量中的 name 会触发多余属性检查。应在这里移除该字段。Pick 只是编译期类型操作,不会从现有运行时对象中自动过滤字段。

Pick<User, "id"> が表すのは id のみ。この新しいリテラルの name は余分な属性として検査される。ここでは name を削除する。Pick は既存オブジェクトの属性を実行時に除去する機能ではない。

TypeScript Handbook

Question 21单选TypeScript · Code review

An async function resolves to a number. Which return annotation is correct?

异步函数最终得到一个数字。正确的返回类型标注是什么?

async 関数が最終的に数値を返す。正しい戻り値の注釈はどれか。

async function loadCount(): number {
  return 42;
}
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 C

The caller receives a Promise<number>, not an immediate number. Inside an async function, returning 42 resolves that promise with 42. The annotation should describe what callers receive.

调用者得到的是 Promise<number>,而非立刻得到数字。在 async 函数内 return 42,会让该 Promise 以 42 为结果完成。返回标注应描述调用者实际收到的类型。

呼び出し側が受け取るのは即座の数値ではなく Promise<number>。async 内の return 42 は Promise を 42 で解決する。注釈も呼び出し側が受け取る型に合わせる。

TypeScript Handbook

Question 22单选TypeScript · Code review

This function should uppercase the resolved text. Which fix handles the promise correctly?

函数应把异步得到的文本转成大写。哪项修复正确处理了 Promise?

解決後のテキストを大文字にしたい。Promise を正しく扱う修正はどれか。

async function readLabel(): Promise<string> {
  const value: Promise<string> = Promise.resolve("ready");
  return value.toUpperCase();
}
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 B

Promise<string> is a promise object, not the eventual string. await obtains the resolved value inside this async function. A type assertion does not wait, unwrap or transform a promise at runtime.

Promise<string> 是 Promise 对象,不是最终的字符串。在该 async 函数里,await 才会取得完成后的值。类型断言不会在运行时等待、解包或转换 Promise。

Promise<string> は Promise オブジェクトであり、最終的な文字列ではない。async 内で await すると解決した値を得られる。型アサーションには待機や実行時の取り出し機能はない。

TypeScript Handbook

Question 23单选TypeScript · Code review

If no user named Kai exists, return an empty string. Which correction handles find safely?

若没有名叫 Kai 的用户,应返回空字符串。如何安全处理 find?

Kai という利用者がいなければ空文字を返す。find を安全に扱う修正はどれか。

function findName(users: { name: string }[]): string {
  return users.find(user => user.name === "Kai").name;
}
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 D

find may return undefined. Optional chaining protects the property access, and ?? supplies the required fallback. filter returns an array, not a single user. A non-null assertion would not handle the missing-user case.

find 可能返回 undefined。可选链保护属性读取,?? 提供约定的默认值。filter 返回数组而非单个用户;非空断言也不能真正处理找不到用户的情况。

find は undefined を返すことがある。?. で属性アクセスを守り、?? で既定値を補う。filter が返すのは配列。非 null アサーションは利用者不在の処理にはならない。

TypeScript Handbook

Question 24单选TypeScript · Code review

Under strict checking, the caught value is unknown. What should the reviewer request before accessing message?

严格检查下,catch 捕获的值是 unknown。访问 message 前应做什么?

strict では catch した値は unknown。message を読む前に何をすべきか。

try {
  throw new Error("Network unavailable");
} catch (error) {
  console.log(error.message);
}
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 A

JavaScript can throw non-Error values too. instanceof Error narrows the caught value and makes message access safe; provide a fallback for other values. A type assertion alone would not validate what was thrown.

JavaScript 也可以抛出非 Error 值。instanceof Error 能缩窄捕获值,让 message 访问安全;其他值应有备用处理。仅靠类型断言无法验证实际抛出的内容。

JavaScript は Error 以外も throw できる。instanceof Error で絞り込めば message を安全に読める。その他の値には別の処理を用意する。アサーションだけでは実際の値を検証できない。

TypeScript Handbook

Question 25单选TypeScript · Code review

A successful result has value; a failed result has error. Which review comment handles both variants?

成功结果有 value,失败结果有 error。哪条意见正确处理了两个分支?

成功なら value、失敗なら error を持つ。両方を処理する正しい指摘はどれか。

type Result =
  | { ok: true; value: string }
  | { ok: false; error: string };
function read(result: Result): string {
  return result.value;
}
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 B

The literal ok property is a discriminator. Checking it narrows Result to the matching member, so only that member's fields are read. Neither value nor error exists on every possible result.

字面量属性 ok 是判别字段。判断它后,Result 会缩窄到对应成员,才能读取该成员独有的字段。value 和 error 都不是所有结果共有的属性。

リテラルの ok が判別子になる。その値で分岐すると対応するメンバーに絞り込まれ、専用の属性を読める。value も error も全パターン共通ではない。

TypeScript Handbook

Question 26单选TypeScript · Code review

Reporter promises callers a callback accepting text. What is wrong with this implementation?

Reporter 向调用者承诺回调接受文本。这个实现的问题是什么?

Reporter のコールバックは文字列を受け取る契約。この実装の問題はどれか。

type Reporter = { report: (message: string) => void };
const reporter: Reporter = {
  report: (message: number) => { console.log(message); }
};
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 D

A caller is entitled to call reporter.report with a string. A number-only implementation cannot fulfill that contract. void describes the return value's usage, not the number or type of parameters.

调用者有权给 reporter.report 传入字符串。只接受 number 的实现无法履行此约定。void 描述返回值的用途,并不决定参数数量或参数类型。

呼び出し側は reporter.report に文字列を渡せる。number 専用の実装では契約を満たせない。void は戻り値の扱いを表し、引数の数や型を決めるものではない。

TypeScript Handbook

Question 27单选TypeScript · Code review

Every palette value must be a string. How should the reviewer fix this satisfies check?

palette 的每个值都必须是字符串。应如何修复这个 satisfies 检查?

palette の各値は文字列にしたい。satisfies の検査を直す修正はどれか。

const palette = {
  red: "#ff0000",
  blue: 123
} satisfies Record<string, string>;
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 A

satisfies checks compatibility without performing a runtime conversion. The number 123 violates the string-value contract. Fix the data rather than removing a useful check or casting the mismatch away.

satisfies 检查类型兼容性,不会进行运行时转换。数字 123 不符合字符串值的约定。应修复数据,而不是删掉有效检查或用断言掩盖不匹配。

satisfies は型の適合を検査し、実行時変換はしない。数値 123 は文字列という契約に違反する。検査を消したりアサーションで隠したりせずデータを直す。

TypeScript Handbook

Question 28单选TypeScript · Code review

With noUncheckedIndexedAccess enabled, the list may be empty. How can firstLabel safely return an uppercase string or an empty string?

开启 noUncheckedIndexedAccess,列表可能为空。firstLabel 如何安全返回大写文本或空字符串?

noUncheckedIndexedAccess 有効で、配列は空かもしれない。大文字の文字列か空文字を安全に返すにはどうするか。

function firstLabel(items: string[]): string {
  return items[0].toUpperCase();
}
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 B

With this flag, an unchecked array lookup may yield undefined. Optional chaining and a fallback handle empty input. readonly prevents mutation through a reference; it does not promise a nonempty array.

该选项启用后,未经检查的数组取值可能为 undefined。可选链和默认值可以处理空输入。readonly 限制通过引用修改数组,不保证数组非空。

この設定では未確認の添字アクセスは undefined を含む。?. と既定値で空入力を扱える。readonly は参照からの変更を制限するだけで、配列が空でないとは保証しない。

TypeScript Handbook

Question 29单选TypeScript · Code review

With exactOptionalPropertyTypes enabled, omit an absent nickname rather than explicitly assigning undefined. Which object matches that requirement?

开启 exactOptionalPropertyTypes;昵称缺失时应省略属性,而不是显式赋值 undefined。哪个对象符合要求?

exactOptionalPropertyTypes 有効。ニックネームがなければ undefined を代入せず属性を省略する。どのオブジェクトが要件に合うか。

type User = { nickname?: string };
const user: User = { nickname: undefined };
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 C

Under this flag, nickname?: string allows omission or a present string, not a present undefined. {} meets the requirement. If explicit undefined were part of the API contract, it would need to be included in the property's value type.

该选项下,nickname?: string 允许省略属性,或提供字符串值,但不允许属性存在且值为 undefined。{} 符合要求。如果 API 确实约定允许显式 undefined,应把它写进属性值类型。

この設定の nickname?: string は省略か文字列を許すが、属性が存在して値が undefined という形は許さない。{} が要件に合う。明示的な undefined を許す契約なら値の型に含める必要がある。

TypeScript Handbook

Question 30单选TypeScript · Code review

This never assignment checks that every action was handled. Which missing implementation should the reviewer request?

这里的 never 赋值用于检查是否处理了所有动作。审查者应要求补上哪个实现?

never への代入で全アクションの処理漏れを検査している。何を追加すべきか。

type Action = { type: "save" } | { type: "delete" };
function handle(action: Action): string {
  switch (action.type) {
    case "save": return "saved";
    default: {
      const unhandled: never = action;
      return unhandled;
    }
  }
}
  1. A
  2. B
  3. C
  4. D
解析 / Explanation

正确答案 A

After save returns, delete still reaches default, so action is not never. Add the missing delete branch. Keeping the never check makes a future unhandled action a type error instead of a silent fall-through.

save 返回后,delete 仍会进入 default,因此 action 还不是 never。应补上 delete 分支。保留 never 检查,可以让未来新增但未处理的动作触发类型错误,而非悄悄漏掉。

save の処理後も delete が default に到達するので action は never ではない。delete 分岐を追加する。never の検査を残せば、将来の追加時も処理漏れを型エラーとして検出できる。

TypeScript Handbook

答题卡 已答 0 · 正确 0 · 错误 0