728x90
이 오류는 JavaScript 및 TypeScript에서 발생하는데, 객체의 선택적 프로퍼티에 값을 할당하려고 할 때 발생합니다. 선택적 프로퍼티 접근은 ?. 연산자를 사용하여 수행되며, 객체가 undefined 또는 null인 경우 프로퍼티 접근을 방지하고 undefined를 반환합니다.
예를 들어, 다음 코드에서 오류가 발생합니다.
const obj = {
nested: {
property: "value",
},
};
obj.nested?.property = "newValue";
이 경우, 선택적 프로퍼티 접근을 사용하지 않고 객체 프로퍼티에 값을 할당하려면 다음과 같이 코드를 변경해야 합니다
if (obj.nested) {
obj.nested.property = "newValue";
}
또는 더 간결하게 작성하려면 다음과 같이 삼항 연산자를 사용할 수 있습니다.
obj.nested ? (obj.nested.property = "newValue") : undefined;
728x90
'JavaScript' 카테고리의 다른 글
Jest import 방법 (With @ 포함 경로 인식) (0) | 2023.04.20 |
---|---|
JS DeepCopy [feat : 변경한 적 없는 객체 값 변경됨 해결] (0) | 2023.04.14 |
Partial<T> 를 활용한 객체 초기화 (0) | 2023.04.12 |
[Error] Hydration failed because the initial UI does not match what was rendered on the server, Text content does not match server-rendered HTML - hydration 비활성화 (0) | 2023.04.07 |
Builder 패턴을 적용한 JS 객체 배열 (with typescript) (0) | 2023.04.06 |
댓글