TypeScript 오류 "The operand of a 'delete' operand of a operator is optional?"의 배후에 있는 논리는 무엇입니까?
이것은 타이프스크립트 코드로 발생하는 새로운 에러입니다.
그 이면에 있는 논리를 이해할 수 없다
문서
/*When using the delete operator in strictNullChecks,
the operand must now be any, unknown, never, or be optional
(in that it contains undefined in the type). Otherwise, use of the delete operator is an error.*/
interface Thing {
prop: string;
}
function f(x: Thing) {
delete x.prop; // throws error = The operand of a 'delete' operator must be optional.
}
그 이면에 있는 논리를 이해할 수 없다
제가 이해한 논리는 다음과 같습니다.
인터페이스Thing
계약서란 (무보증, 무보증)를 갖는 것을 요구하는 계약서입니다.prop
로서string
.
자산을 제거하면 계약은 더 이상 실행되지 않습니다.
삭제해도 유효하게 하려면 , 를 사용해 옵션으로서 선언해 주세요.?
:prop?: string
이것이 이전 버전의 TypeScript에서 오류를 일으키지 않았다는 사실에 놀랐습니다.
이 배경에는 다음과 같은 옵션 속성을 사용하여 인터페이스를 구현해야 합니다.
interface Thing {
prop?: string;
}
// OR
interface Thing {
prop: string | undefined;
}
function f(x: Thing) {
delete x.prop;
}
그래서 인터페이스의 계약은 깨지지 않을 거야.
퀵픽스
의 유형을 변경할 수 있습니다.x
부분:
function f(x: Partial<Thing>) {
delete x.prop;
}
그러나 저는 보통 알려지지 않은 코드에서 전달된 오브젝트를 변환(수정)하는 것을 좋아하지 않습니다.그 대신 새로운 오브젝트를 만듭니다.
function f(x: Thing) {
const y = { ...x } as Partial<Thing>;
delete y.prop;
}
부터Partial
모든 속성을 옵션으로 만듭니다.이것에 의해, 에서 임의의 속성을 삭제할 수 있습니다.y
.
권장된
좀 더 구체적으로 말하면 (1개의 라이너) 또는 (type-fest에서)를 사용할 수 있습니다.
const y = { ...x } as PartialBy<Thing, 'prop1' | 'prop2'>;
그렇게 되면prop1
그리고.prop2
옵션이지만 다른 모든 속성은 원래대로 유지합니다.
메모
위에, 나는const y = value as Type;
읽기가 더 쉬우니까하지만 당신은 아마도const y: Type = value;
그 대신 타이프 체크가 더 잘 되니까요.
이게 도움이 될지도 몰라
const { propToDelete, ...otherProps} = yourObject
return otherProps
이를 통해 otherProps 객체를 중단 없이 사용할 수 있습니다.
다른 실장(존재하는 경우):
interface Thing {
prop: string;
}
interface PropoptionalThing {
prop?: string;
}
function f(x: Thing): PropoptionalThing {
let tmp: PropoptionalThing = x;
delete tmp.prop;
return tmp;
}
그prop
에 있어서의 재산.Thing
인터페이스를 옵션으로 표시해야 합니다.?
마크.
그럼 너의Thing
인터페이스는 다음과 같아야 합니다.
interface Thing {
prop?: string;
}
언급URL : https://stackoverflow.com/questions/63702057/what-is-the-logic-behind-the-typescript-error-the-operand-of-a-delete-operato
'programing' 카테고리의 다른 글
spread 연산자 vs array.concat() (0) | 2023.02.26 |
---|---|
본문을 유효한 json으로 읽는 방법 (0) | 2023.02.26 |
jQuery ajax 콜은 PATCH를 지원합니까? (0) | 2023.02.26 |
Oracle 선택 항목에서 더 많은 열이 있는 테이블에 삽입 (0) | 2023.02.26 |
경고: imagejpeg() [function: imagejpeg]: gd-jpeg: JPEG 라이브러리에서 복구할 수 없는 오류가 보고됩니다. (0) | 2023.02.26 |