TypeScript에서 인터페이스 파일 정의를 기반으로 개체를 만들려면 어떻게 해야 합니까?
다음과 같은 인터페이스를 정의했습니다.
interface IModal {
content: string;
form: string;
href: string;
$form: JQuery;
$message: JQuery;
$modal: JQuery;
$submits: JQuery;
}
다음과 같은 변수를 정의합니다.
var modal: IModal;
하지만 모달 속성을 설정하려고 하면 다음과 같은 메시지가 나타납니다.
"cannot set property content of undefined"
인터페이스를 사용하여 modal 객체를 설명해도 괜찮습니까?설명할 경우 어떻게 작성해야 합니까?
다른 곳에서 "모달" 변수를 만들고 TypeScript에 모든 작업을 수행할 경우 다음을 사용합니다.
declare const modal: IModal;
실제로 TypeScript에서 IModal의 인스턴스가 되는 변수를 작성하려면 변수를 완전히 정의해야 합니다.
const modal: IModal = {
content: '',
form: '',
href: '',
$form: null,
$message: null,
$modal: null,
$submits: null
};
타입 어설션과 할 , 타입 어설션의에 예기치 되지 않게 , 에러가 이 있습니다.이것은, 액세스시에 예기치 않은 장소에서 정의되지 않게 되어, 런타임 에러가 발생할 가능성이 있기 때문입니다.modal.content(계약서에 기재되어 있는 부동산은) 등입니다.
const modal = {} as IModal;
클래스 예시
class Modal implements IModal {
content: string;
form: string;
href: string;
$form: JQuery;
$message: JQuery;
$modal: JQuery;
$submits: JQuery;
}
const modal = new Modal();
"이거 정말 인터페이스의 복제품이야"라고 생각할 수도 있지만, 정답입니다.Modal 클래스가 IModal 인터페이스의 유일한 구현일 경우 인터페이스를 완전히 삭제하고 다음을 사용할 수 있습니다.
const modal: Modal = new Modal();
보다는
const modal: IModal = new Modal();
인터페이스의 빈 객체가 필요한 경우 다음 작업을 수행할 수 있습니다.
var modal = <IModal>{};
데이터 구조화에 클래스 대신 인터페이스를 사용하는 장점은 클래스에 메서드가 없는 경우 컴파일된 JS에 빈 메서드로 표시됩니다.예:
class TestClass {
a: number;
b: string;
c: boolean;
}
으로 정리하다.
var TestClass = (function () {
function TestClass() {
}
return TestClass;
})();
아무 가치도 없어요반면, 인터페이스는 JS에는 전혀 표시되지 않지만 데이터 구조화와 유형 확인의 이점을 제공합니다.
React를 사용하는 경우 파서는 기존 캐스트 구문에 의해 초크되므로 .tsx 파일에서 사용하는 대체 방법이 도입되었습니다.
let a = {} as MyInterface;
https://www.typescriptlang.org/docs/handbook/jsx.html
기본적으로 다섯 가지 다른 선택지가 있다고 생각합니다.당신이 성취하고 싶은 목표에 따라 그 중에서 선택하는 것은 쉬울 수 있다.
대부분의 경우 TypeScript를 사용하여 유형 검사를 적용하므로 클래스를 사용하고 인스턴스화하는 가장 좋은 방법입니다.
interface IModal {
content: string;
form: string;
//...
//Extra
foo: (bar: string): void;
}
class Modal implements IModal {
content: string;
form: string;
foo(param: string): void {
}
}
다른 방법으로 인터페이스에서 오브젝트를 쉽게 작성할 수 있는 경우에도 다른 문제에 오브젝트를 사용하고 있어 인터페이스의 과분할이 발생하지 않는 경우 인터페이스를 분할하는 것을 검토할 필요가 있습니다.
interface IBehaviour {
//Extra
foo(param: string): void;
}
interface IModal extends IBehaviour{
content: string;
form: string;
//...
}
한편, 예를 들면, 유닛의 코드 테스트중에(문제의 분리를 빈번히 실시하지 않는 경우는), 생산성을 위해서 단점을 받아들일 수 있는 경우가 있습니다.주로 대형 서드파티 *.d.ts 인터페이스용으로 mock을 작성하기 위해 다른 방법을 적용할 수 있습니다.또, 모든 대규모 인터페이스에 대해서, 항상 완전한 익명 오브젝트를 실장하는 것은 귀찮을 가능성이 있습니다.
이 경로에서 첫 번째 옵션은 빈 개체를 만드는 것입니다.
var modal = <IModal>{};
둘째, 인터페이스의 필수 부분을 완전히 실현합니다.서드파티 JavaScript 라이브러리를 호출하는 경우에도 유용하지만 이전과 같이 클래스를 만드는 것이 좋다고 생각합니다.
var modal: IModal = {
content: '',
form: '',
//...
foo: (param: string): void => {
}
};
셋째, 인터페이스의 일부만 생성하여 익명 객체를 만들 수 있지만, 이렇게 하면 계약을 이행할 책임이 있습니다.
var modal: IModal = <any>{
foo: (param: string): void => {
}
};
인터페이스가 옵션인 경우에도 JavaScript 코드로 변환되지 않기 때문에 TypeScript는 현명하고 일관되게 사용한다면 새로운 수준의 추상화를 제공할 수 있습니다.대부분의 경우 자신의 코드에서 그것들을 제거할 수 있다고 해서 그렇게 해서는 안 된다고 생각합니다.
할수있습니다
var modal = {} as IModal
다음은 또 다른 접근법입니다.
이렇게 ESLint 친화적인 개체를 만들 수 있습니다.
const modal: IModal = {} as IModal;
또는 인터페이스에 기초한 디폴트인스턴스 및 적절한 디폴트인스턴스(있는 경우)
const defaultModal: IModal = {
content: "",
form: "",
href: "",
$form: {} as JQuery,
$message: {} as JQuery,
$modal: {} as JQuery,
$submits: {} as JQuery
};
그런 다음 일부 속성을 재정의하는 것만으로 기본 인스턴스의 변형
const confirmationModal: IModal = {
...defaultModal, // all properties/values from defaultModal
form: "confirmForm" // override form only
}
인터페이스를 사용하는 방법에는 5가지가 있습니다.
interface IStudent {
Id: number;
name: string;
}
Method 1. all fields must assign data.
const obj1: IStudent = { Id: 1, name: 'Naveed' };
Method 2. my favorite one
const obj2 = { name: 'Naveed' } as IStudent ;
Method 3.
const obj3 = <IStudent >{name: 'Naveed'};
Method 4. use partial interface if all fields not required.
const obj4: Partial<IStudent > = { name: 'Naveed' };
Method 5. use ? Mark with interface fields if all fields not required.
const obj5: IStudent = { name: 'Naveed' };
맨 위에 똑같은 답을 못 찾았고 내 답은 다르니까.하고 있습니다.
modal: IModal = <IModal>{}
질문에는 TypeScript 사용법이 포함되어 있기 때문에 치환합니다.
var modal: IModal;
타고
let modal: IModal = {} as IModal;
질문에 대답해야 합니다.
지금까지 게시된 많은 솔루션은 유형 어설션을 사용하기 때문에 구현에서 필요한 인터페이스 속성이 생략된 경우 컴파일 오류를 발생시키지 않습니다.
기타 견고하고 콤팩트한 솔루션에 관심이 있는 고객:
옵션 1: 인터페이스를 구현하는 어나니머스 클래스를 인스턴스화합니다.
new class implements MyInterface {
nameFirst = 'John';
nameFamily = 'Smith';
}();
옵션 2: 유틸리티 기능을 만듭니다.
export function impl<I>(i: I) { return i; }
impl<MyInterface>({
nameFirst: 'John';
nameFamily: 'Smith';
})
해서 기본값을 설정할 수 .Class.
클래스 생성자 없음:
interface IModal {
content: string;
form: string;
href: string;
isPopup: boolean;
};
class Modal implements IModal {
content = "";
form = "";
href: string; // will not be added to object
isPopup = true;
}
const myModal = new Modal();
console.log(myModal); // output: {content: "", form: "", isPopup: true}
클래스 컨스트럭터 포함
interface IModal {
content: string;
form: string;
href: string;
isPopup: boolean;
}
class Modal implements IModal {
constructor() {
this.content = "";
this.form = "";
this.isPopup = true;
}
content: string;
form: string;
href: string; // not part of constructor so will not be added to object
isPopup: boolean;
}
const myModal = new Modal();
console.log(myModal); // output: {content: "", form: "", isPopup: true}
let deletedQuestionsDto = { examId: this.examId, questionId: q.id } as DeletedQuestionsDto;
개체를 만드는 데 클래스가 필요하지 않습니다.다음과 같이 지시할 수 있습니다.
interface IModal {
content: string;
form: string;
}
onButtonSaveClick() {
let myModalClass: IModal = {
content: 'foo content',
form: 'foo form'
}
}
인터페이스를 사용하여
class Modal() {
constructor(public iModal: IModal) {
//You now have access to all your interface variables using this.iModal object,
//you don't need to define the properties at all, constructor does it for you.
}
}
여기 내가 자주 사용하는 또 다른 해결책이 있다.다만, 좋은 프랙티스가 될지 어떨지는 잘 모르겠습니다만, 없는 경우는 아래의 코멘트를 부탁드립니다.
/// Interface
export default interface BookInterface {
title: string,
author: string,
id: any
}
/// Creating Class
export class BookClass implements BookInterface {
title: string;
author: string;
id: any;
constructor(title: string, author: string, id: any) {
this.title = title;
this.author = author;
this.id = id;
}
}
/// How to use it
let book: BookInterface = new BookClass(title, author, id);
감사합니다:)
언급URL : https://stackoverflow.com/questions/13142635/how-can-i-create-an-object-based-on-an-interface-file-definition-in-typescript
'source' 카테고리의 다른 글
| MUI 스타일로 소품 전달 (0) | 2023.02.18 |
|---|---|
| Typescript에서 오류를 발생시키는 함수를 선언하는 방법 (0) | 2023.02.16 |
| Django REST Framework를 사용하여 POST를 심플하게 하는 방법CSRF 토큰이 없거나 잘못되었습니다. (0) | 2023.02.16 |
| string | null 형식의 인수는 string 유형의 파라미터에 할당할 수 없습니다.유형 'null'은 유형 'string'에 할당할 수 없습니다. (0) | 2023.02.16 |
| MongoDB 기본 데이터베이스 경로는 무엇입니까? (0) | 2023.02.16 |