유형에서는 Literal Type도 허용합니다. 아래와 같은 코드를 확인해봅시다.
function testUnion(
input: string | string[],
resultType: "as-number" | "as-array"
) {
if (typeof input === "string" && resultType === "as-array") return [input];
else return input;
}
위코드에서 타입을 literal 으로 지정하였습니다. 사용법은 직관적으로 간단합니다. 마치 literal으로 정의된 타입이 있는 것 처럼 사용하시면 됩니다. 입력시 해당 타입을 직접입력해줘야 합니다. 오타나 허용되지 않은 resultType은 에러를 일으킵니다.
type
Aliasestype Combineable = string | string[];
function testUnion(input: Combineable, resultType: "as-number" | "as-array") {
if (typeof input === "string" && resultType === "as-array") return [input];
else return input;
}
console.log(testUnion("2", "as-number"));
이전에 있던 코드를 위코드로 전환 할수 있습니다. 위 코드에서 보다시피 타입 스크립트에서는 type
이라는 키워드로 string | string[]
조건을 Combineable
이라는 타입을 정의 했습니다. 그리고 그것을 정말 타입처럼 사용하였으며 VScode에서도 해당 코드를 type
이라고 인식하였습니다.
물론 자바스크립트에서는 이러한 기능은 없지만 타입스크립트에서 컴파일시 지원하는 기능일 뿐 입니다.
type Combineable = string | string[];
type resultType = "as-number" | "as-array";
function testUnion(input: Combineable, resultType: resultType) {
if (typeof input === "string" && resultType === "as-array") return [input];
else return input;
}
console.log(testUnion("2", "as-number"));
위 코드에서는 type
을 literal로 정의 했습니다. 이렇게 정의한 타입은 완전히 새로운 타입입니다. 이러한 타입을 Custom type으로서 사용할 수 있습니다. 위 코드를 보면 기존에 정의 되어 있던 literal type을 새로운 resultType으로 정의한다음 사용하였습니다.
function testFunc(input1: number, input2: number) {
return input1 + input2;
}
function printResult(result: number) {
console.log(result);
}
void
는 any
의 반대입니다. 그 어떤 반환형도 허용하지 않는 다는 것이죠. undefined는 아무값도 할당이 안된다는 뜻으로서 void
랑은 다릅니다.
위 코드에서 printResult 함수는 return
을 하지 않았습니다. 그 어떤것도 반환하지 않는 함수로서 함수의 반환형은 void
라는 키워드가 됩니다. 타입스크립트에서는 함수의 반환형을 명시적으로 적어주지 않아도 유형추론을 통해 해당함수의 반환형을 알수 있습니다.
함수의 return
문의 유무를 통해 함수의 반환형이 void
가 될 수 있습니다.
let funcType;
funcType = testFunc;
funcType = 5;
console.log(funcType(8, 8)); // error
보통 자바스크립트에서는 위 코드에서 error
가 발생할 것이라는 것을 당연히 알것입니다. funcType은 5로 할당이 되어 더이상 testFunc을 가르키고 있지 않기 때문입니다. 하지만 타입스크립트에서는 이러한 변수에 타입을 명시함으로서 funcType = 5
에서부터 에러를 체크할 수 있습니다.
let funcType: Function;
funcType = testFunc;
funcType = 5;
console.log(funcType(8, 8));
이러한 함수의 타입을 정하는 것은 함수의 매개변수의 타입과 반환형의 타입까지 명시할 수 있습니다.
let funcType: (a: number, b: number) => number;
funcType = testFunc;
console.log(funcType(8, 8));
위 코드에서는 funcType에 넣어질 함수의 유형을 넣음으로서 정해진 타입의 함수만 들어갈 수 있도록 정의 해놓았습니다. 위 코드에서는 에러가 나지 않습니다.
function testFunc(input1: number, input2: number) {
return input1 + input2;
}
function printResult(result: number) {
console.log(result);
}
let funcType: (a: number, b: number) => number;
funcType = printResult; // error
funcType = testFunc;
console.log(funcType(8, 8));
위 코드에서는 에러가 일어납니다. printResult는 반환형이 없어 반환형을 void
로 명시를 해놓아야 하기 때문입니다. 따라서 정해진 유형의 함수타입이 아니므로 error
를 반환합니다.
함수에 대한 명시적인 타입을 넣고 구현을 한다면 역시 콜백함수에 대해서도 명시적인 타입 설정을 할 수 있습니다. 콜백 함수를 설정 할 때 콜백 함수 자체의 유형의 반환형을 void로 설정했음에도 콜백함수가 반환형있다면 해당 반환형을 아무 에러없이 받아버립니다. 반환형이 없다면 반환형을 사용하지 않는 코드를 사용해야 합니다.
function testFunc(
input1: number,
input2: number,
cb: (result: number) => void
) {
const result = input1 + input2;
const answer = cb(result);
console.log("answer :", answer);
return result;
}
const callBack = function (res: number) {
console.log("callBack :", res);
return 20;
};
testFunc(8, 8, callBack);
any
type과 비슷한 타입인 unknown
type 입니다. 어느 타입이나 올수 있으나 결정적인 차이는 any는 그어느 때든 어떤 타입이 와도 상관없지만 unknown
타입은 해당타입이 string
이나 확실한 타입임이 확인되어야 할당될 수 있습니다.
let userInput: unknown;
let userName: string;
userInput = 5;
userInput = "Max";
userName = userInput; //error
에러가 나는 이유는 userName은 string
타입으로서 userInput의 타입이 unknown
이므로 무엇인지 확인되지 않았기 때문에 에러가 난것입니다. 그렇다면 typeof
를 이용해서 타입을 확인하고 할당하면 어떻게 될까요?
let userInput: unknown;
let userName: string;
userInput = 5;
userInput = "Max";
if (typeof userInput === "string") {
userName = userInput;
}
userInput의 타입이 'string' 일 경우에만 userName 에 userInput을 할당하도록 하였으므로 에러가 없는 것을 확인 할 수 있습니다. 이러한 에러는 any
타입에서는 생기지 않습니다.
let userInput: any;
let userName: string;
userInput = 5;
userInput = "Max";
userName = userInput;
any
타입은 어느 타입도 될 수 있기때문에 userName 또한 userName이 string도 할당가능하기 때문에 에러가 나오지 않는 것 입니다.
never
타입은 함수가 항상 에러를 반환하거나 무한루프이거나 결론이 나지 않는 등 함수가 완벽하게 종결되는 시점이 없는 타입임을 명시할 때 사용합니다. 반환형 타입의 일종입니다.
function error(message: string): never {
console.log(message);
} // error never
이렇게 함수가 끝나는 끝점에 도달할 경우 never
타입을 명시할 수 없습니다.
function testFunc1(message: string): never {
throw new Error("Always occurs errors!");
}
function testFunc2(message: string): never {
while(true){
}
}
testFunc1 의 경우에는 항상 throw Error를 발생시키므로 함수 자체적으로 끝점에 도달하여 끝나는 경우가 아닙니다. 따라서 never
타입으로 명시할 수 있습니다.
testFunc2 의 경우에는 무한루프에 빠지게 되므로 never
타입을 명시할 수 있습니다.
never
타입을 명시하지 않을 경우에는 타입스크립트는 함수의 반환형을 void
로 유형추론 합니다.