IT이야기

파괴 할당과 선택적 체인을 어떻게 결합할 수 있는가?

cyworld 2022. 3. 24. 22:06
반응형

파괴 할당과 선택적 체인을 어떻게 결합할 수 있는가?

일부 선택적 필드와 해당 유형의 변수를 포함하는 TypeScript 인터페이스:

interface Foo {
    config?: {
        longFieldName?: string;
    }
}

declare let f: Foo;

라고 표현하고 싶다.longFieldName동명의 변수에

만약config선택사항이 아니라 파괴 할당을 사용하여 반복하지 않고longFieldName하지만 사실이야. 그래서 유형 오류가 생겼어

const { longFieldName } = f.config;
     // ~~~~~~~~~~~~~  Property 'longFieldName' does not exist on type '{ longFieldName?: string | undefined; } | undefined'.

선택적 체인을 사용하여 간결하게 처리할 수 있다.undefined사례:

const longFieldName = f?.config.longFieldName;  // OK, type is string | undefined

하지만 이제 나는 반복해야 한다.longFieldName.

내 케이크도 먹을 수 있을까?선택적 체인을 사용하여 다음 작업을 처리할 수 있는가?undefined반복하지 않는 경우longFieldName그렇지 않다면, 가장 간결하고 직관적인 해결책은 무엇인가?놀이터 링크를 참조하십시오.

단락 평가를 사용하여 다음과 같은 경우 폴백 값(빈 물체)을 얻으십시오.f?.config에 대한 표현.undefined:

const { longFieldName } = f?.config || {};

기본값을 사용할 수 있다.

const Foo = {}
const { config: { longFieldName = "" } = {} } = Foo
console.log(longFieldName) //''

참조URL: https://stackoverflow.com/questions/58866519/how-can-i-combine-destructuring-assignment-and-optional-chaining

반응형