8월 24일에 TypeScript 4.4 버전이 새로 릴리스 되었습니다.
새로 추가된 기능들을 알아보도록 하겠습니다.
function foo(arg: unknown) {
const isString = typeof arg === 'string';
// 타입 검사하여 할당한 변수를 보고 타입 추론 가능
if (isString) {
console.log(arg.toUpperCase());
}
}
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'square'; sideLength: number };
function area(shape: Shape): number {
// 검사대상 parameter를 extract 해서 사용 가능함
const { kind } = shape;
const isCircle = kind === 'circle';
if (isCircle) {
// We know we have a circle here!
return Math.PI * shape.radius ** 2;
} else {
// We know we're left with a square here!
return shape.sideLength ** 2;
}
}
function doSomeChecks(
inputA: string | undefined,
inputB: string | undefined,
shouldDoExtraWork: boolean
) {
// 다른 변수로 검사 결과를 할당해도 사용 가능
const mustDoWork = inputA && inputB && shouldDoExtraWork;
if (mustDoWork) {
// We can access 'string' properties on both 'inputA' and 'inputB'!
const upperA = inputA.toUpperCase();
const upperB = inputB.toUpperCase();
// ...
}
}
// Depth가 늘어나도 분석이 가능함
function func(x: string | number | boolean) {
const isString = typeof x === 'string';
const isNumber = typeof x === 'number';
const isStringOrNumber = isString || isNumber;
if (isStringOrNumber) {
x; // Type of 'x' is 'string | number'.
} else {
x; // Type of 'x' is 'boolean'.
}
}
interface 선언 시에 key를 특정한 값으로 고정하지 않고, 타입만을 지정해주는 문법
interface IndexSignature {
[key: number]: string;
}
// Symbol 사용 가능
interface Colors {
[sym: symbol]: number;
}
const red = Symbol('red');
const green = Symbol('green');
const blue = Symbol('blue');
const colors: Colors = {};
colors[red] = 255; // Assignment of a number is allowed
const redVal = colors[red]; // 'redVal' has the type 'number'