언어/TypeScript

[TypeScript] 기본

홍시_코딩기록 2023. 12. 14. 22:16

- 타입 스크립트는 타입을 정확히! 명시해주어야함.

- string, number, boolean, null, undefined ...등

 

만약 이런 객체를 써야한다면?

let data:Restaurant = {
    name: '식당',
    category: 'western',
    address: {
        city: 'incheon',
        detail: 'somewhere',
        zipCode: 123123
    },
    menu:[
            {
                name: 'rose pasta',
                price:2000,
                category: 'pasta'
            },
            {
                name: '갈릭',
                price:2000,
                category: '스테이크'
            }
        ]
}

 

 

Restaurant.ts 새 페이지로 만들어서 객체마다 타입을 명시해주고 address와 menu같은 경우엔 새로운 타입을 만들어서 보기 좋게 만들어줌.

export type Restaurant = {
    name: string;
    category: string;
    address: Address;
    menu: Menu[]
};

export type Address = {
    city: string;
    detail: string;
    zipCode?:number;  //Omit필요 없이 물음표로도 가능함( 주의! zipcode가 반드시 있어햐 할 상황에도 넘어갈 수가 있음)
}

export type Menu = {
    name: string;
    price: number;
    category: string;
}

export type AddressWithOutZip = Omit<Address, 'zipCode'>  //타입 하나 빼고싶을 때
export type RestaurantOnlyCate = Pick<Restaurant, 'category'> //하나만 가져오고 싶을 때

 

 

App.tsx


const App:React.FC = () => {
    const [myRestaurant, setMyRestaurant] = useState<Restaurant>(data);
    const changeAddress = (address:Address) => {
        setMyRestaurant({...myRestaurant, address:address})
    }

    const showBestMenuName = (name:string) => {
        return name
    }

    return (
        <div className="App">
            <Store info={myRestaurant} changeAddress={changeAddress}/>
            <BestMenu name="불고기피자" category="피자" showBestMenuName={showBestMenuName} />
        </div>
    )
}

 

 

BestMenu.tsx


type OwnProps = Omit<Menu, 'price'> & {  // Menu를 가져오지만 price 항목을 빼고싶을 
    showBestMenuName(name:string):string
}

const BestMenu:React.FC<OwnProps> = (props) => {
  return (
    <div>
        <p>{props.name}</p>
        <p>{props.category}</p>
    </div>
  )
}

 

Store.tsx


interface OwnProps {
    info:Restaurant,
    changeAddress(adress:Address):void
}

const Store:React.FC<OwnProps> = (props) => {
  return (
    <div>{props.info.name}</div>
  )
}

'언어 > TypeScript' 카테고리의 다른 글

[TypeScript] 공부중..  (1) 2023.12.29