TypeScript를 쓴다면 JavaScript에서 unit test를 쓸 필요가 없다. TypeScript가 자동적으로 체크해 준다.
This is especially useful when you’re using a UI library and need to transform data. For example, if you’re using React, you’ll need to transform data in state updates.
we can use mapped types like Readonly to convert one type to another type.
// Readonly<...> makes each property readonly
type Todo = Readonly<{
id: number
text: string
done: boolean
}>
// 위 <...>은 아래와 같다.
type Todo = {
readonly id: number
readonly text: string
readonly done: boolean
}
readonly는 array의 push와도 같이 쓰일 수 있다.
Type assertions
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
// as Type을 더 추천한다.
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
ref1는 readonly용 react가 관리할 built-in ref attributes에 전달하기 위한 것? (Response handles for your current value setting)
ref2는 ref2.current를 mutable하게 해주고 사용자가 직접관리하는 instance variables 를 위한 것이다.
네? 뭐라구여???
useEffect
함수 또는 undefined 이외에 다른 것이 return 되지 않도록 주의한다.
setTimeout을 사용하는 경우 number가 return되기 때문에 curly brace로 꼭 감싸자.
useRef
function TextInputWithFocusButton() {
// 초기값은 null, HTMLInputElement를 찾고 있다고 TypeScript에 말함
const inputEl = React.useRef<HTMLInputElement>(null);
const onButtonClick = () => {
// strict null 체크는 inputEl와 current가 존재하는지 확인해야한다.
// 존재하면 HTMLInputElement type이므로 따라서 method focus를 가진다. 🙂 Yay
if (inputEl && inputEl.current) {
inputEl.current.focus();
}
};
return (
<>
{/* 또한 inputEl는 input요소만 사용할 수 있다? focus 때문인가 */}
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
useReducer
type AppState = {};
type Action =
| { type: "SET_ONE"; payload: string }
| { type: "SET_TWO"; payload: number };
export function reducer(state: AppState, action: Action): AppState {
switch (action.type) {
case "SET_ONE":
return {
...state,
one: action.payload, // `payload` is string
};
case "SET_TWO":
return {
...state,
two: action.payload, // `payload` is number
};
default:
return state;
}
}
Discriminated Unions(유니온 식별)은 singleton types, union types, type guards, 및 type aliases을 결합하여 discriminated unions, tagged unions, 또는 algebraic(대수의) data type으로 불리는 고급 패턴을 빌드할 수 있다.