Typerscript를 사용하여 객체 유형을 정의하는 방법

11608 단어 TypeScripttech
대상 유형에서 변수를 정의할 때 typescript를 사용하면 대상 유형을 어떻게 지정합니까?🤔 그렇게 생각해서 알아봤어요.
결론적으로 먼저 "interface hoge"또는 "type hoge"형식으로 유형을 정의합니다.
// interfaceを使うときは下記のように定義
interface Person {
  name: string;
  age: number;
}

// typeを使うときは下記のように定義
type Person = {
  name: string;
  age: number;
}

// 関数で変数を定義するときは引数にオブジェクトの型を指定
function greet(person: Person) {
  return "Hello " + person.name;
}
cf.interface와 type을 사용하지 않을 때 다음과 같이 정의를 직접 지정할 수 있습니다.
하지만 대상 속성의 수가 늘어나면 어렵기 때문에 인터페이스 or type을 사용하는 것이 좋습니다.
function greet(person: { name: string; age: number }) {
  return "Hello " + person.name;
}

type과interface를 사용하는 좋은 질문


차이점은 공식문장.에 쓰여 있으니 시간 나면 읽어주세요(아직 완전히 이해가 안 됐어요)📚
조사 후 젠에서 이 일에 대한 언급유익한 소식을 발견했다.
저자의 견해는 어느 것이든 대용할 수 있다면 type이 좋다는 것이다.
stackoverflow도 화제다.
이 내용을 참고하여 앞으로 필요하지 않으면 type으로만 설명하겠습니다.

기타 사용 방법

  • 「?」대화상자가 옵션으로 바뀌어 '속성' 을 지정하지 않아도 오류가 발생하지 않습니다.
  • type personalInfo = {
      name: string;
      height?: number;
      weight?: number;
    }
    
    // ? がついているプロパティは指定しなくてもエラーにならない!!
    const person1:personalInfo = {name:'yamada'}
    const person2:personalInfo = {name:'tanaka', height:170}
    const person3:personalInfo = {name:'suzuki', weight:63}
    
    // nameの値を指定していないためエラー
    const person4:personalInfo = {height:181}
    // personalInfoにないプロパティを指定しているためエラー
    const person5:personalInfo = {name:'ikeda', age:32}
    
  • readonly로 읽기 전용
  • type personalInfo = {
      readonly name: string;
      age:number;
    }
    
    const person1:personalInfo = {name:'yamada',age:36}
    
    // 読み取り専用なので表示は可能
    console.log(personal1.name)
    // error 再代入は不可
    person1.name = 'kimura'
    // ageはreadonlyでないため再代入可能
    person1.age = 45
    
    주의,readonly는 별명을 통과하면 다시 대입할 수 있습니다.
    (다음 예 참조)
    type Person = {
      name: string;
      age: number;
    }
    
    type ReadonlyPerson = {
      readonly name: string;
      readonly age: number;
    }
    
    let writablePerson: Person = {
      name: "Person McPersonface",
      age: 42,
    };
    
    let readonlyPerson: ReadonlyPerson = writablePerson;
    
    console.log(readonlyPerson.age); // prints '42'
    // writableはreadonlyでないためエラーにならない!
    writablePerson.age++;
    // readonlyでも値が増えてしまう
    console.log(readonlyPerson.age); // prints '43'
    

    작업 환경


    다음 환경에서 작동 여부를 확인했다.
    codesandbox

    참고 자료


    공식.
    type과interface의 차이
    Type Script에서 type 및 interface를 사용하는 질문
    stackoverflow에서의 토론

    좋은 웹페이지 즐겨찾기