TypeScriptfunction consoleLogText(text) {
text.split("");
return text;
}
consoleLogText("string");
consoleLogText(123);
function consoleLogNumber(text) {
return text;
}
consoleLogNumber(123);
function consoleLogTypeString(text: string | number) {
if (typeof text === "string") {
text.split("");
}
if (typeof text === "number") {
text.toString();
}
return text;
}
const stringType = consoleLogTypeString("string");
stringType.split(""); // 에러 발생
const numberType = consoleLogTypeString(123);
stringType.toLocaleString();
'string | number' 형식에 'split' 속성이 없습니다.
'number' 형식에 'split' 속성이 없습니다.ts(2339)
function genericType<T>(text: T): T {
return text;
}
const stringGeneric = genericType<string>("string");
stringGeneric.split("");
const numberGeneric = genericType<number>(123);
numberGeneric.toString();
인터페이스 예제
interface Dropdown<T> {
value: T;
selected: boolean;
}
const objectStringConst: Dropdown<string> = {
value: "string",
selected: true,
};
const objectNumberConst: Dropdown<number> = {
value: 123,
selected: true,
};