// function getNumber(): Promise<number>
async function getNumber() {
return 42;
}
const getNumber = async () => 42;
// Type is () => Promise<number>
const getNumber = () => Promise.resolve(42); // Type is () => Promise<number>
//Do this
const _cache: {[url: string]: string} = {};
async function fetchWithCache(url: string) {
if (url in _cache) {
return _cache[url];
}
const response = await fetch(url);
const text = await response.text();
_cache[url] = text;
return text;
}
let requestStatus: 'loading' | 'success' | 'error';
async function getUser(userId: string) {
requestStatus = 'loading';
const profile = await fetchWithCache(`/user/${userId}`);
requestStatus = 'success';
}
타입 추론에서 문맥이 어떻게 쓰이는지 주의하자 (상수로 쓰는지, 변수로 뽑아서 쓰는지)
얕은참조인지, 깊은참조인지 잘보고, 오류가 발생하면 타입선언을 추가해라
상수 단언을 사용하면 정의한 곳이 아니라 사용한 곳에서 오류가 뜨므로 주의해라
type Language = 'JavaScript' | 'TypeScript' | 'Python';
function setLanguage(language: Language) {}
function panTo(where: [number, number]) {}
panTo([10, 20]); // OK
const loc = [10, 20]; //number[] 로 추론해버림
panTo(loc);
// ~~~ Argument of type 'number[]' is not assignable to
// parameter of type '[number, number]'
//이럴땐
const loc = [10, 20] as const // readonly[10,20] 이라고 추론해버린다.
//그러므로 최선은 panTo에 where시그니처에 readonly [number,number]라고 해주는 수밖에 없다.
function panTo(where: readonly [number, number]) { /* ... */ }
const loc = [10, 20, 30] as const; // 에러남
panTo(loc);
type language = 'JS'|'TS'
interface gLanguage {
language: language
organization : string
}
function complain(lan : gLanguage) {}
일때
const ts = {
language: 'TS' //
organization: 'MS'
}
complain(ts) 는 에러
// ts에서 language: string으로 추론되기 때문에