let num: string | number | object | any = 3;
const arr: string[] = ['a'];
const arr: number[] = [3];
function sum(x:number,y:number): number {
return x + y;
}
number 타입의 숫자를 반환
interface Shape {
getArea():number;
}
class Circle implements Shape {
constructor(public radius:number){
this.radius = radius;
}
getArea() {
return this.radius * this.radius * Math.PI;
}
}
class Rectangle implements Shape {
constructor(private width:number,private height:number) {
this.width = width;
this.height = height;
}
getArea(): number {
return this.width * this.height;
}
}
const circle:Circle = new Circle(5);
const rectangle:Rectangle = new Rectangle(20, 20);
function getCircleArea(circle:Circle) {
return circle.getArea();
}
const shapes: Shape[] = [circle, rectangle];
shapes.forEach(shape=>{
console.log(shape.getArea());
})
implement 를 사용하여 interface 상속가능
interface Person<T> {
list:T
}
const Person:Person<string> = {
list : 'learn generics'
}
T라는 타입을 list에 할당가능
function merge<T1, T2> (a:T1, b:T2) {
return {
...a,
...b,
}
}
const merged = merge(2,'3');
function wrap<T> (param:T) {
return {
param
}
}
const wrapped = wrap(20)
타입이 동적이면서 타입을 지키고 싶을떄 사용을 한다.