interface는 js에는 존재하지 않음. 즉 컴파일 타임에만 필요함
interface Person1 {
name: string;
age: number;
}
interface Person2 {
name: string;
age?: number;
}
function hello1(person: Person1): void {
console.log(`안녕하세요! ${person.name} 입니다.`)
}
function hello2(person: Person2): void {
console.log(`안녕하세요! ${person.name} 입니다.`)
}
hello1({name: "Mark"}); //error
hello2({name: "Anna"}); //okay
//? 사용시 있어도 되고, 없어도 됨
interface Person3 {
name: string;
age?: number;
[index: string]: any;
}
const p32: Person3 = {
name: "Anna",
systers: ["Sung", "Chan"]
}
interface Person4 {
name: string;
age?: number;
hello(): void;
}
const p51: Person4 = {
name: 'Mark',
age: 30,
hello: function(): void{
console.log(`안녕하세요! ${this.name} 입니다.`)
},
}
const p52: Person4 = {
name: 'Mark',
age: 30,
hello(): void{
console.log(`안녕하세요! ${this.name} 입니다.`)
},
}
interface IPerson1 {
name: string;
age?: number;
hello(): void;
}
//interface를 이용해서 class를 만듬 (implements)
class Person implements IPerson1 {
name: string;
age?: number | undefined;
constructor(name: string) {
this.name = name;
}
hello(): void {
console.log(`안녕하세요! ${this.name} 입니다.`)
}
}
const person = new Person('Mark');
person.hello();
interface IPerson2 {
name: string;
age?: number;
}
interface IKorean extends IPerson2 {
city: string;
}
const k: IKorean = {
name: 'hun',
city: 'seoul',
};
interface HelloPerson {
(name: string, age?: number): void;
}
const helloPerson: HelloPerson = function(name: string) {
console.log(`안녕하세요 ${name} 입니다. `)
}
수정 불가능한 값
//function
// type alias
type EatType = (food: string) => void;
// interface
interface IEat {
(food: string): void;
}
--------------------------------------------------
//Array
// type alias
type PersonList = string[];
// interface
interface IPersonList {
[index: number]: string;
}
--------------------------------------------------
//intersection
interface ErrorHandling {
success: boolean;
error?: { message: string };
}
interface ArtistsData {
artists: { name: string }[];
}
// type alias
type ArtistsResponseType = ArtistsData & ErrorHandling;
// interface
interface IArtistsResponse extends ArtistsData, ErrorHandling {}
let art: ArtistsResponseType;
let iar: IArtistsResponse;
--------------------------------------------------
//union types
interface Bird {
fly(): void;
layEggs(): void;
}
interface Fish {
swim(): void;
layEggs(): void;
}
type PetType = Bird | Fish;
//interface IPet extends PetType {}// error
//class Pet implements PetType {} // error
--------------------------------------------------
// deckaration merging - interface
interface MergingInterface {
a: string;
}
interface MergingInterface {
b: string;
}
let mi: MergingInterface;
//mi.a mi.b 가능 (합쳐짐)
//alias는 불가