StudyForYou / ouahhan-typescript-with-react

우아한 타입스크립트 with 리액트 스터디 레포 🧵
4 stars 0 forks source link

#15 [4장_3] 주어진 코드를 보고 Shape 타입을 정의하고, area 함수에서 타입 좁히기를 사용하여 각 도형의 넓이를 계산하세요. #27

Closed hyeyoonS closed 2 months ago

hyeyoonS commented 3 months ago

❓문제

주어진 코드를 보고 Shape 타입을 정의하고, area 함수에서 타입 좁히기를 사용하여 각 도형의 넓이를 계산하세요.

interface Circle {
  radius: number;
}

interface Rectangle {
  width: number;
  height: number;
}

type Shape = // write your code here

function area(shape: Shape): number {
  // write your code here
}

🎯답변 요약

🎯답변

interface Circle {
  radius: number;
}

interface Rectangle {
  width: number;
  height: number;
}

type Shape = Circle | Rectangle

function area(shape: Shape): number {
    if ('width' in shape) return shape.width * shape.height;
    return 3.14 * shape.radius ** 2
}
drizzle96 commented 3 months ago
interface Circle {
  radius: number;
}

interface Rectangle {
  width: number;
  height: number;
}

type Shape = Circle | Rectangle

function area(shape: Shape): number {
  if ('radius' in shape) return Math.PI * shape.radius ** 2
  return shape.width * shape.height
}
qooktree1 commented 3 months ago
interface Circle {
  radius: number;
}

interface Rectangle {
  width: number;
  height: number;
}

type Shape = Circle | Rectangle

function area(shape: Shape): number {
    if ('width' in shape) return shape.width * shape.height;
    return 3.14 * shape.radius ** 2
}
summerkimm commented 3 months ago
interface Circle {
  radius: number;
}

interface Rectangle {
  width: number;
  height: number;
}

type Shape = Circle | Rectangle

function area(shape: Shape): number {
    if ('height' in shape) return shape.width * shape.height;
    return 3.14 * shape.radius ** 2
}
hyeyoonS commented 3 months ago
interface Circle {
  radius: number;
}

interface Rectangle {
  width: number;
  height: number;
}

type Shape = Circle | Rectangle

function area (shape: Shape): number {
  if ('radius' in shape) return  3.14 * shape.radius ** 2
  return shape.width * shape.height
}