타입스크립트 타입 단언 예제
타입스크립트에는 `as` 키워드가 있다.
`as` 키워드는 개발자가 특정 값의 타입을 정확히 알고 있는 경우, 타입스크립트의 컴파일러에 해당되는 타입을 직접 알려주고 명시하는 기능이다.
원하는 타입을 지정할 때 `as` 키워드를 사용할 수 있으며, 실제 데이터를 변환하는 것이 아니라 타입 검사 기준만 변경하게 된다.
값 as 타입⊙
const value: unknown = "TypeScript";
const textLength = (value as string).length;
console.log(textLength); // 10⊙
const value: unknown = 100;
const text = value as string;
console.log(text.toUpperCase());⊙
const value = 100 as unknown as string;⊙
const value = 100;
const text = String(value);
console.log(text); // "100"⊙
const message: unknown = "안녕하세요";
// 오류
// console.log(message.length);⊙
const message: unknown = "안녕하세요";
const length = (message as string).length;
console.log(length);⊙
const message: unknown = "안녕하세요";
const text = message as string;
console.log(text.length);⊙
const message: unknown = "안녕하세요";
if (typeof message === "string") {
console.log(message.length);
}⊙
let userId: string | number = "user-100";
const stringId = userId as string;
console.log(stringId.toUpperCase());⊙
let userId: string | number = 100;
if (typeof userId === "string") {
console.log(userId.toUpperCase());
} else {
console.log(userId.toFixed(0));
}⊙
const emailInput = document.getElementById(
"email"
) as HTMLInputElement;
console.log(emailInput.value);⊙
<input id="email" type="email" />⊙
const element = document.getElementById("email");
if (element instanceof HTMLInputElement) {
console.log(element.value);
}⊙
const emailInput = document.getElementById(
"email"
) as HTMLInputElement | null;
if (emailInput) {
console.log(emailInput.value);
}⊙
interface User {
id: number;
name: string;
email: string;
}⊙
const data: unknown = {
id: 1,
name: "Kim",
email: "kim@example.com",
};
const user = data as User;
console.log(user.name);⊙
const data: unknown = {
nickname: "Kim",
};
const user = data as User;
// 실행 결과가 undefined일 수 있음
console.log(user.email);⊙
interface User {
id: number;
name: string;
email: string;
}
function isUser(value: unknown): value is User {
if (typeof value !== "object" || value === null) {
return false;
}
const candidate = value as Record<string, unknown>;
return (
typeof candidate.id === "number" &&
typeof candidate.name === "string" &&
typeof candidate.email === "string"
);
}
const data: unknown = {
id: 1,
name: "Kim",
email: "kim@example.com",
};
if (isUser(data)) {
console.log(data.email);
} else {
console.error("올바르지 않은 사용자 데이터입니다.");
}⊙
interface Profile {
name: string;
age: number;
}
const profile = {} as Profile;
profile.name = "Lee";
profile.age = 30;⊙
interface Profile {
name: string;
age: number;
}
const profile = {} as Profile;
console.log(profile.name.toUpperCase());⊙
interface Profile {
name: string;
age: number;
}
const profile: Profile = {
name: "Lee",
age: 30,
};⊙
const status = "success" as const;⊙
const config = {
mode: "dark",
retry: 3,
} as const;⊙
type Config = {
readonly mode: "dark";
readonly retry: 3;
};⊙
const config = {
mode: "dark",
retry: 3,
} as const;
// 오류
// config.mode = "light";⊙
const coordinates = [37.5, 127.0] as const;
// 타입: readonly [37.5, 127.0]⊙
const value: unknown = "TypeScript";
const text1 = value as string;
const text2 = <string>value;⊙
// 권장
const text = value as string;
댓글
댓글 쓰기