📍 덕 타이핑 vs 구조적 타이핑?

덕 타이핑과 구조적 타이핑 두 가지는 비슷하면서, 근본적으로 다름. 그 전에, 명목적 타이핑부터 살펴보겠음.

명목적 타이핑 (Normal Typing)

int x = 10;

덕 타이핑(duck typing)

“만약 어떤 새가 오리처럼 걷고, 헤엄치고, 꽥꽥거리는 소리를 낸다면, 나는 그 새를 오리라고 부를 것이다.”

function greet(person) {
  console.log(`Hello, ${person.name}!`);
}

const person1 = { name: "Alice", age: 30 };
const person2 = { name: "Bob", occupation: "Engineer" };

greet(person1); // Hello, Alice! 출력
greet(person2); // Hello, Bob! 출력

구조적 타이핑 (structurally typing)

type WithFirstName = {
  firstName: string;
};

type WithLastName = {
  lastName: string;
};

const hasBoth = {
  firstName: "Lucille",
  lastName: "Clifton",
};

let withFirstName: WithFirstName = hasBoth;

let withLastName: WithLastName = hasBoth;

hasBoth 변수는 명시적으로 선언되지 않았음에도 두 개의 별칭 객체 타입을 모두 가지므로 두 개의 별칭 객체 타입 내에 선언된 변수를 모두 제공할 수 있음

📍 사용 검사

1번: 필수 속성 검사