interface PaintOptions {
shape: Shape;
xPos?: number;
yPos?: number;
}
// 해결책 1 - 타입 체크
function paintShape(opts: PaintOptions) {
let xPos = opts.xPos === undefined ? 0 : opts.xPos;
let yPos = opts.yPos === undefined ? 0 : opts.yPos;
// ...
}
// 해결책 2 - 기본값 설정
function paintShape({ shape, xPos = 0, yPos = 0 }: PaintOptions) {
let xPos = opts.xPos === undefined ? 0 : opts.xPos;
let yPos = opts.yPos === undefined ? 0 : opts.yPos;
// ...
}
//구조분해 문법 내부에 타입을 작성하지 말 것
function draw({ shape: Shape, xPos: number = 100 /*...*/ }) {
render(shape); //Cannot find name 'shape'. Did you mean 'Shape'?
render(xPos); //Cannot find name 'xPos'.
interface SomeType {
readonly prop: string;
}
function doSomething(obj: SomeType) {
console.log(`prop has the value '${obj.prop}'.`);
// Cannot assign to 'prop' because it is a read-only property.
obj.prop = "hello";
}
interface Home {
readonly resident: { name: string; age: number };
}
function visitForBirthday(home: Home) {
// 가능
console.log(`Happy birthday ${home.resident.name}!`);
home.resident.age++;
}
function evict(home: Home) {
// Cannot assign to 'resident' because it is a read-only property.
home.resident = {
name: "Victor the Evictor",
age: 42,
};
}
interface Person {
name: string;
age: number;
}
interface ReadonlyPerson {
readonly name: string;
readonly age: number;
}
let writablePerson: Person = {
name: "Person McPersonface",
age: 42,
};
// 타입이 같다고 간주
let readonlyPerson: ReadonlyPerson = writablePerson;
console.log(readonlyPerson.age); // prints '42'
writablePerson.age++;
// readonly임에도 불구하고 shallow copy를 했기에 writablePerson 값 변화에 영향을 받게 됨
console.log(readonlyPerson.age); // prints '43'
interface StringArray {
[index: number]: string;
}
const myArray: StringArray = getStringArray();
const secondItem = myArray[1]; //string
interface NumberDictionary {
[index: string]: number;
length: number;
// Property 'name' of type 'string' is not assignable to 'string' index type 'number'.
name: string;
}
// ok
interface NumberOrStringDictionary {
[index: string]: number | string;
length: number;
name: string;
}
interface BasicAddress {
name?: string;
street: string;
city: string;
country: string;
postalCode: string;
}
interface AddressWithUnit extends BasicAddress {
unit: string;
}
// 두개 이상의 타입도 상속 가능
interface Colorful {
color: string;
}
interface Circle {
radius: number;
}
interface ColorfulCircle extends Colorful, Circle {}
const cc: ColorfulCircle = {
color: "red",
radius: 42,
};
interface Colorful {
color: string;
}
interface Circle {
radius: number;
}
type ColorfulCircle = Colorful & Circle; //color, redius 속성을 가짐
interface Box<Type> {
contents: Type;
}
//제네릭 함수와의 결합
function setContents<Type>(box: Box<Type>, newContents: Type) {
box.contents = newContents;
}
type OrNull<Type> = Type | null;
type OneOrMany<Type> = Type | Type[];
type OneOrManyOrNull<Type> = OrNull<OneOrMany<Type>>;// OneOrMany<Type> | null
type OneOrManyOrNullStrings = OneOrManyOrNull<string>;// OneOrMany<string> | null
Array<Type>
타입으로 대체 가능함, 여기서 Array 타입은 제네릭 타입임Map<K, V>
Set<T>
Promise<T>
형식으로 타입이 정의되어 있음function doSomething(value: Array<string>) {
// ...
}
let myArray: string[] = ["hello", "world"];
// Array<string>와 string[]은 같은 타입
doSomething(myArray);
doSomething(new Array("hello", "world"));
// readonly string[]과 동일한 타입
function doStuff(values: ReadonlyArray<string>) {
const copy = values.slice();
console.log(`The first value is ${values[0]}`);
// Property 'push' does not exist on type 'readonly string[]'.
values.push("hello!");
}
// consturctor 사용 불가
new ReadonlyArray("red", "green", "blue");
// 'ReadonlyArray' only refers to a type, but is being used as a value here.
// 배열을 직접 할당해주어야함
const roArray: ReadonlyArray<string> = ["red", "green", "blue"];
let x: readonly string[] = [];
let y: string[] = [];
x = y; // ok
// The type 'readonly string[]' is 'readonly' and cannot be assigned to the mutable type 'string[]'.
y = x;
type StringNumberPair = [string, number];
function doSomething(pair: StringNumberPair) {
const a = pair[0]; //string
const b = pair[1]; //number
// Tuple type '[string, number]' of length '2' has no element at index '2'.
const c = pair[2];
}
doSomething(["hello", 42]);
function doSomething(stringHash: [string, number]) {
const [inputString, hash] = stringHash;
console.log(inputString); //string
console.log(hash); //number
}
type Either2dOr3d = [number, number, number?];
function setCoordinate(coord: Either2dOr3d) {
const [x, y, z] = coord; //z: number | undefined
//length: 2 or 3
console.log(`Provided coordinates had ${coord.length} dimensions`);
}
type StringNumberBooleans = [string, number, ...boolean[]];
type StringBooleansNumber = [string, ...boolean[], number];
type BooleansStringNumber = [...boolean[], string, number];
// 함수의 인자로 들어갈 때에는 다음과 같이 작성
function readButtonInput(...args: [string, number, ...boolean[]]) {
const [name, version, ...input] = args;
// ...
}
// 다음 표현과 결국 같은 말
function readButtonInput(name: string, version: number, ...input: boolean[]) {
// ...
}
function doSomething(pair: readonly [string, number]) {
pair[0] = "hello!"; //Cannot assign to '0' because it is a read-only property.
// 배열에 const를 붙이면 readonly tuple로 취급됨
let point = [3, 4] as const;
function distanceFromOrigin([x, y]: [number, number]) {
return Math.sqrt(x ** 2 + y ** 2);
}
/*
Argument of type 'readonly [3, 4]' is not assignable to parameter of type '[number, number]'.
The type 'readonly [3, 4]' is 'readonly' and cannot be assigned to the mutable type '[number, number]'.
*/
distanceFromOrigin(point);
}
출처:
https://www.typescriptlang.org/docs/handbook/2/objects.html