강의

멘토링

커뮤니티

Inflearn Community Q&A

wlgpalth4374's profile image
wlgpalth4374

asked

[Renewal] TypeScript All-in-One: Part 1. Basic Grammar

key-value 타입 자동추론 질문드립니다

Written on

·

243

·

Edited

0

const StreamingProtocolList = ['HLS', 'DASH', 'CMAF'] as const
export type UnionOfTuple<T extends readonly any[]> = T[number]
export type IStreamingProtocol = UnionOfTuple<typeof StreamingProtocolList>
export const isCMAFProtocol = (protocol: IStreamingProtocol) => protocol === 'CMAF'

export interface IEndpoint {
    ce_id?: string
    ce_description: string
    ce_drm_yn: YN
    ce_type: IStreamingProtocol
    ce_hls_manifest_id: string | null
}

위와같이 타입을 만들어놓고 컴포넌트단에서 onchange시에 key값과 value값을 인자로 던졌을때, 해당 key값에 대한 value타입을 자동추론하려고 합니다.

 

 const onChangeHandler = useCallback(
        <K extends keyof IEndpoint>({ key, value }: { key: K; value: IEndpoint[K] }) => {
            setState(prev => {
                if (key === 'ce_type') {
                    return { ...prev, ce_hls_manifest_id: isCMAFProtocol(value) ? 4464 : null, [key]: value }
                } else {
                    return { ...prev, [key]: value }
                }
            })
        },
        [],
    )

 제가원하는건 위의라인에 isCMAFProtocol에 들어가는 value가 IStreamingProtocol타입으로 자동추론되는건데

TS2345: Argument of type string | number is not assignable to parameter of type 'HLS' | 'DASH' | 'CMAF
라 발생하며 추론을 못하는 상황입니다.

 

이런 경우에는 제가 IStreamingProtocol에 대한 custom 타입가드함수를 만들어서 강제로 타입을 전환시켜야 되는 방법밖에 없을까요?

 

typescript

Answer 1

1

zerocho님의 프로필 이미지
zerocho
Instructor

가장 쉽게 강제로 변환하는 건 다음 코드고요.

ce_hls_manifest_id: isCMAFProtocol(value as IEndpoint['ce_type']) ? 4464 : null

깔끔한 방법은 저도 좀 고민좀 해보겠습니다.

wlgpalth4374님의 프로필 이미지
wlgpalth4374
Questioner

넵 감사합니다!!

wlgpalth4374's profile image
wlgpalth4374

asked

Ask a question