feat(i18n): 문구 보간 파라미터를 catalog의 {이름}에서 만든다 (0929/08-03)
문제: 보간 파라미터 타입이 플랫폼 파일의 닫힌 목록 `MessageParameters`에만
있다. 목록에 없는 기능 키는 `[parameters?: never]`가 된다. 그래서
`formatMessage("ko-KR", "reference.list.resultCount")`는 타입 검사를
통과하고 실행하면 대체 문구를 돌려주며, `{ count: 1 }`을 넣으면 TS2345로
거절된다. 샘플은 타입 없는 `resolveMessage`로 우회했고, tech-log는 템플릿
파일에 키 11개를 넣었다.
고른 방법: (B) catalog가 `as const`이므로 ko-KR 문자열 literal의
`{이름}`에서 `MessageArguments<Key>`를 만든다. 값 타입은
`string | number`다. 값 타입을 좁히고 싶은 키만 `MessageParameters`로
덮어쓴다. 덮어쓰기는 catalog 파라미터와 교집합이라 좁히기만 한다. 덮어쓴
항목이 catalog 문자열과 어긋나도 catalog의 자리표시자는 계속 필수다.
`ParameterlessMessageKey`도 "자리표시자가 없는 키"로 같은 규칙에서
만든다. 기존 덮어쓰기 8개는 값 타입을 좁히므로 그대로 둔다.
새 개념이 없고, 기능이 템플릿 파일을 고치지 않는다.
버린 대안: (C) 기능 모듈이 파라미터 타입을 따로 선언하고 설치 조립이
교집합을 만든다. 값 타입을 정확히 쓸 수 있지만 catalog와 선언을 따로
맞춰야 한다.
위험·한계:
- 값 타입이 `string | number`로 넓다. 좁히려면 `MessageParameters`에
덮어쓴다.
- 자리표시자는 ko-KR 문자열에서 읽는다. 다른 locale과의 일치는
`tests/unit/i18n-contract.test.ts`의 parity 검사가 지킨다.
- ICU 복수형·select처럼 `{이름}`으로 표현하지 못하는 문구는 다루지
않는다(VD-06 재검토 조건).
- 타입 검사 비용(`tsc -p tsconfig.app.json --extendedDiagnostics`):
Types 287,440 -> 289,911(+0.9%), Instantiations 721,217 -> 748,663
(+3.8%). 실행 시간은 load average 9~21에서 전·후 모두 1.0~2.6초로
흔들려 차이를 구분할 수 없었다.
- 기능 키 검사(`tests/features/reference-feature/feature-module.test.ts`)는
샘플과 함께 지워지도록 샘플 테스트 폴더에 두었다. 플랫폼 fixture는
샘플 키에 기대지 않는다.
검증:
- RED: `npx tsc -p tsconfig.test.json --noEmit`
feature-module.test.ts(23,5): error TS2578: Unused '@ts-expect-error'
feature-module.test.ts(26,60): error TS2345: Argument of type
'{ count: number; }' is not assignable to parameter of type 'undefined'.
- GREEN: 같은 명령 오류 0. app·node·recipes 타입 검사 통과.
- `check:types:fixture:i18n-params` fixture: 기존 3줄은 TS2554/TS2345로
계속 실패하고, 더한 덮어쓰기 좁힘 줄은 TS2322로 실패한다.
- vitest: tests/features/reference-feature, i18n-contract,
locale-platform 19 files 97 tests 통과.
- 샘플 목록 화면이 타입 있는 `message()`로 결과 수를 그린다.
Refs: docs/reviews/2026-09-29-maturity-review/08-presentation.md 08-03
This commit is contained in:
@@ -21,9 +21,11 @@ JavaScript에 분산돼 있었다. 날짜는 일부 application mapper에서 고
|
||||
2. `MessageKey`는 한국어 canonical catalog에서 도출하며 영어와 RTL smoke
|
||||
catalog는 `satisfies Record<MessageKey, string>`으로 compile-time parity를
|
||||
강제한다.
|
||||
3. 보간이 필요한 key는 `MessageParameters`에 key별 parameter object를
|
||||
선언한다. 잘못된 key, 누락·초과 parameter는 TypeScript negative fixture가
|
||||
거절한다.
|
||||
3. 보간 parameter는 catalog 문자열의 `{이름}`에서 도출한다(0929/08-03).
|
||||
값 타입은 `string | number`다. 값 타입을 좁히고 싶은 key만
|
||||
`MessageParameters`에 key별 parameter object를 선언한다. 기능 catalog의
|
||||
key도 같은 규칙을 쓰므로 기능이 이 파일을 고치지 않는다. 잘못된 key,
|
||||
누락·초과 parameter는 TypeScript negative fixture가 거절한다.
|
||||
4. 기본 locale은 `ko-KR`, fallback locale도 `ko-KR`이다. 알려지지 않은 locale은
|
||||
language fallback 후 `ko-KR`로 정규화한다. 알려지지 않은 key와 누락 보간은
|
||||
raw key나 외부 값을 출력하지 않고 안전한 공통 fallback을 반환한다.
|
||||
|
||||
@@ -5,16 +5,13 @@ import {
|
||||
Button,
|
||||
CollectionPage,
|
||||
} from "../../../presentation/design-system/index.ts";
|
||||
import {
|
||||
resolveMessage,
|
||||
useLocale,
|
||||
} from "../../../presentation/i18n/index.ts";
|
||||
import { useLocale } from "../../../presentation/i18n/index.ts";
|
||||
import { useReferenceFailureAction } from "./use-reference-failure-action.ts";
|
||||
import { useReferenceFeature } from "./use-reference-feature.ts";
|
||||
|
||||
export default function ReferenceResourcePage() {
|
||||
const navigate = useNavigate();
|
||||
const { locale, message } = useLocale();
|
||||
const { message } = useLocale();
|
||||
const { filters, query } = useReferenceFeature();
|
||||
const failureAction = useReferenceFailureAction(query.state.failure);
|
||||
|
||||
@@ -45,10 +42,9 @@ export default function ReferenceResourcePage() {
|
||||
}
|
||||
resultCount={
|
||||
// 08-09. Counted only from a settled result: a loading, idle or
|
||||
// failed list has nothing to count. Feature keys carry no parameter
|
||||
// types, so the count goes through the untyped resolver.
|
||||
// failed list has nothing to count.
|
||||
query.state.base === "success" || query.state.base === "empty"
|
||||
? resolveMessage(locale, "reference.list.resultCount", {
|
||||
? message("reference.list.resultCount", {
|
||||
count: query.data?.length ?? 0,
|
||||
})
|
||||
: null
|
||||
|
||||
@@ -14,6 +14,26 @@ export const SUPPORTED_LOCALES = Object.freeze([
|
||||
export type SupportedLocale = (typeof SUPPORTED_LOCALES)[number];
|
||||
export type TextDirection = "ltr" | "rtl";
|
||||
|
||||
/**
|
||||
* 0929/08-03. The `{name}` placeholders of a catalog string literal. The
|
||||
* catalogs are `as const`, so platform and feature keys share this one rule
|
||||
* and a feature never edits this file to type its own messages. The ko-KR
|
||||
* template is the source; the locale parity test keeps the others equal.
|
||||
*/
|
||||
type TemplatePlaceholder<Template> =
|
||||
Template extends `${string}{${infer Name}}${infer Rest}`
|
||||
? Name | TemplatePlaceholder<Rest>
|
||||
: never;
|
||||
type MessagePlaceholder<Key extends MessageKey> = TemplatePlaceholder<
|
||||
(typeof KO_MESSAGES)[Key]
|
||||
>;
|
||||
|
||||
/**
|
||||
* Narrower value types for keys that want them. A placeholder's value is
|
||||
* `string | number` otherwise. An entry only narrows: the catalog's
|
||||
* placeholders are still required, so an entry that drifts from its catalog
|
||||
* string cannot drop one.
|
||||
*/
|
||||
export type MessageParameters = Readonly<{
|
||||
"action.closeNamed": { title: string };
|
||||
"action.alertCloseNamed": { title: string };
|
||||
@@ -24,15 +44,19 @@ export type MessageParameters = Readonly<{
|
||||
"home.runtime.summary": { buildId: string; releaseId: string };
|
||||
"boot.supportReference": { reference: string };
|
||||
}>;
|
||||
export type ParameterlessMessageKey = Exclude<
|
||||
MessageKey,
|
||||
keyof MessageParameters
|
||||
>;
|
||||
export type ParameterlessMessageKey = {
|
||||
[Key in MessageKey]: [MessagePlaceholder<Key>] extends [never] ? Key : never;
|
||||
}[MessageKey];
|
||||
|
||||
type CatalogParameters<Key extends MessageKey> = Readonly<
|
||||
Record<MessagePlaceholder<Key>, string | number>
|
||||
>;
|
||||
export type MessageArguments<Key extends MessageKey> =
|
||||
Key extends keyof MessageParameters
|
||||
? [parameters: MessageParameters[Key]]
|
||||
: [parameters?: never];
|
||||
[MessagePlaceholder<Key>] extends [never]
|
||||
? [parameters?: never]
|
||||
: Key extends keyof MessageParameters
|
||||
? [parameters: CatalogParameters<Key> & MessageParameters[Key]]
|
||||
: [parameters: CatalogParameters<Key>];
|
||||
|
||||
const PLACEHOLDER_PATTERN = /\{([a-zA-Z][a-zA-Z0-9]*)\}/g;
|
||||
const FALLBACK_LOCALE = "ko-KR" as const;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { loadFeatureRuntime } from "../../../src/features/feature-module.ts";
|
||||
import { REFERENCE_FEATURE_MODULE } from "../../../src/features/reference-feature/feature-module.ts";
|
||||
import { formatMessage } from "../../../src/presentation/i18n/index.ts";
|
||||
|
||||
describe("REFERENCE_FEATURE_MODULE", () => {
|
||||
it("owns every install-time contribution under one feature id", async () => {
|
||||
@@ -15,4 +16,14 @@ describe("REFERENCE_FEATURE_MODULE", () => {
|
||||
expect(runtime.contractContributions.length).toBeGreaterThan(0);
|
||||
expect(Object.keys(runtime.apiContract.apiOperations).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("types a feature message's parameters from its catalog placeholders", () => {
|
||||
// 0929/08-03. `check:types:test` is the assertion: the feature declares
|
||||
// `{count}` only in its catalog, and the typed call must require it.
|
||||
// @ts-expect-error the catalog's {count} makes the parameter required.
|
||||
formatMessage("ko-KR", "reference.list.resultCount");
|
||||
expect(
|
||||
formatMessage("ko-KR", "reference.list.resultCount", { count: 1 }),
|
||||
).toBe("총 1개 항목");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,3 +3,7 @@ import { formatMessage } from "../../../src/presentation/i18n/index.ts";
|
||||
formatMessage("en-US", "route.documentTitle");
|
||||
formatMessage("en-US", "route.documentTitle", { title: "Missing app name" });
|
||||
formatMessage("en-US", "action.retry", { unexpected: "value" });
|
||||
// 0929/08-03. Parameters come from the catalog's `{name}` placeholders, and a
|
||||
// `MessageParameters` entry still narrows the value type. The feature-key case
|
||||
// lives in tests/features/reference-feature so it leaves with the sample.
|
||||
formatMessage("en-US", "form.remaining", { count: "3" });
|
||||
|
||||
Reference in New Issue
Block a user