[Typescript] My knowledge of how to handle your custom type :->

未分類

Typescript makes our codes more reliable. But for the bignner as me it's prety hard to understand what type is, what the diffrence is from type and interface, the thoghts of intersection type and union type. I will break them down and show you how I am understanding these features.

type

At first in Typescript, we won't see class very much because of type.

In Javascript when you want to create an object you don't need to make a class.

In Typescript, of cource you can define object with type. you can write to define object like the below.

type PersonType = {
   name: String
   age: number
}

type BossType = {
   doSomething: () => void
}

type ManagementType = PersonType & BossType

const kaito: ManagementType = {
   name: 'kitaya',
   age: 27,
   doSomething: () => {console.log('Hello')}
}

then you can make an instance like this.

let kitaya: Person = {
    name: 'kaito',
    age: 27
}

interface

As you know, interface is a contract of how the object behaive. Actualy you can define as below.

interface Person {
   name: string
   age: number
}

interface Boss extends Person {
   doBigThing: (judge: boolean) => void
}

const kaito: Boss = {
    name: "kitaya",
    age: 27,
    doBigThing: () => {console.log('Hello')}
}

If you want to add elements that you want the stuff to implement you will connect interfaces by using extends.

コメント

タイトルとURLをコピーしました