Typerscript를 사용하여 객체 유형을 정의하는 방법
11608 단어 TypeScripttech
결론적으로 먼저 "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}
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에서의 토론
Reference
이 문제에 관하여(Typerscript를 사용하여 객체 유형을 정의하는 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://zenn.dev/mo_ri_regen/articles/typescript-object텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)