러닝 타입스크립트를 읽고 요약한 내용입니다.
function identity(input) {
return input;
}
identity("abc");
identity(123);
identity("quote: blahblah");
function identity<T>(input: T) {
return input;
}
const numeric = identity("me"); // 타입: "me"
const stringy = identity(123); // 타입 123
function logWrapper<Input>(callback: (input: Input) => void) {
return (input: Input) => {
console.log("Input", input);
callback(input);
};
}
logWrapper<string>((input: string) => {
console.log(input.length);
})
logWrapper<string>((input: boolean) => {
// Argument of type '(input: boolean) => void' is not assignable to parameter of type '(input: string) => void'.
// Types of parameters 'input' and 'input' are incompatible.
// Type 'string' is not assignable to type 'boolean'.(2345)
})
function makeTuple<Fisrt, Second>(first: Fisrt, second: Second) {
return [first, second] as const;
}
let tuple = makeTuple(true, "abc");
function makePair<Key, Value>(key: Key, value: Value) {
return { key, value };
}
// 별도의 타입 인수가 제공되지 않음
makePair("abc", 123);
// 두 개의 타입 인수가 제공됨
makePair<string, number>("abc", 123);
makePair<"abc", 123>("abc", 123);
// Expected 2 type arguments, but got 1.
makePair<string>("abc", 123);
interface Box<T> {
inside: T;
}
let stringyBox: Box<string> = {
inside: "abc",
};
let numberBox: Box<number> = {
inside: 123,
};
// Type 'boolean' is not assignable to type 'number'.
let incorrectBox: Box<number> = {
inside: false,
}
interface Array<T> {
// 마지막 요소 제거하고 반환
// 배열이 비어 있는 경우 undefined 반환하고 배열은 수정되지 않음
pop(): T | undefined;
// 배열의 마지막에 새로운 요소를 추가하고 배열의 길이를 반환
// @param items 배열에 추가된 새로운 요소
push(...itemA: T[]): number;
}
interface LinkedNode<Value> {
next?: LinkedNode<Value>;
value: Value;
}
function getLast<Value>(node: LinkedNode<Value>): Value {
return node.next ? getLast(node.next) : node.value;
}
// 유추된 Value 타입 인수: Date
let lastDate = getLast({
value: new Date("09-13-1993"),
})
// 유추된 Value 타입 인수: string
let lastFruit = getLast({
next: {
value: "banana";
},
value: "apple",
});
// 유추된 Value 타입 인수: number
let lastMisMatch = getLast({
next: {
value: 123,
},
value: false,
// Type 'boolean' is not assignable to type 'number'.
})
interface CreateLike<T> {
content: T;
}
// Generic type 'CreateLike<T>' requires 1 type argument(s).
let missingGeneric: CreateLike = {
inside: "??"
}
type Nullish<T> = T | null | undefined;
type CreatesValue<Input, Output> = (input: Input) => Output;
// 타입: (input: string) => number
let creator: CreatesValue<string, number>;
creator = text => text.length; // ok
creator = text => text.toUpperCase();