function getMyInfo(info: {name: string}){
console.log(info.name);
}
getMyInfo({name: 'dacircle'}) //dacircle
//예시)
interface info {
name: string;
age: number;
}
function getMyInfo(info: info) {
console.log(info.name);
}
const myInfo = {
name: "dacircle",
age: 25
};
console.log(getMyInfo(myInfo)); //dacircle
//잘못된 예시)
interface info {
name: string;
age: number;
}
const yourInfo: info = {
name: "yourName",
age: 27,
address: "경기도",
};
Type '{ name: string; age: number; address: string; }' is not assignable to type 'info'.
Object literal may only specify known properties, and 'address' does not exist in type 'info'.
: 객체 리터럴은 정해진 속성만 지정할 수 있으며 'info' 형식에는 'address'가 없습니다.
→ 객체 리터럴로 바로 할당할 때 나오는 메세지이다.
interface info {
name: string;
age: number;
}
const yourInfoList = {
name: "yourName",
age: 27,
address: "경기도",
};
const yourInfo: info = yourInfoList;
: 에러가 나지 않는다..!
interface info {
readonly name: string;
age: number;
address?: string;
}
interface defaultInfo {
name: string;
age: number;
}
interface anotherInfo extends defaultInfo{
address: string;
phone: string;
family: string[];
}
const myInfo: defaultInfo = {
name: 'dacircle',
age: 25,
};
const yourInfo: anotherInfo = {
name: 'yourName',
age: 27,
address: '경기도',
phone: '010-1111-1111',
family: ['mother','father','sister'],
}
console.log(myInfo.name); //dacircle
console.log(yourInfo.family); //(3) ["mother", "father", "sister"]
interface defaultInfo {
name: string;
age: number;
}
interface anotherInfo extends defaultInfo{
family: string[];
}
type Info = defaultInfo & anotherInfo;
const yourInfo: Info = {
name: 'yourName',
age: 27,
family: ['mother','father','sister'],
}
console.log(yourInfo.name); //yourName
console.log(yourInfo.age); //27
console.log(yourInfo.family); //(3) ["mother", "father", "sister"]
interface info {
name: string;
age: number;
}
let i: info;
let myInfo = {
name: 'dacircle',
age: 25,
address: '경기도',
};
i = myInfo;
i = {
name: "dacircle",
age: 25,
address: "경기도"
}
: 에러!
i와 myInfo의 타입은 다르지만 호환이 되었다!!!
- 호환 조건
- 할당하고자 하는 타입(myInfo)이 할당될 타입의 구조(i)와 내부 타입이 같아야 한다.
→ Structural typing
{name:string, age:number}
이다.{name:string , age:number , address:string}
가 된다!