• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

filter<string> 관련 질문

23.03.06 17:49 작성 조회수 303

0

const predicate = ((i) : i is string => typeof i === "string");
const filtered1 = [1,'2',3].filter(predicate);
const filtered2 = [1,'2',3].filter<string>((i) => typeof i === "string")

filtered1 에서 위의 코드가 되는 이유는 i is string 이라고 지정해줘서 value is string 인 타입가드가 성립하는건데

filtered2 에서 에러가 나는건 i 값에 대한 타입을 정확히 안정해줘서 i 타입에 따라 true or false를 판별해야 하기 때문에 (i : number | string) => boolean 이 뜨고 결국 value is string 이라는 형식 조건자와 일치하지 않아 에러가 뜨는걸로 이해했는데 혹시 맞나요..?

그리고 별도로 그럼 is 가 들어간 커스텀 타입가드는 해당 타입이 뭔지 제한해주는(?) 역할로 이해하고 있었는데 정확하게는 위의 코드로 예시로 들자면 i의 타입을 string으로 고정시켜주는게 맞나요?

 

답변 1

답변을 작성해보세요.

1

filtered2에서는 <string>을 직접 넣어주셨는데, <string>을 직접 넣는 경우는 무조건 리턴값이 value is string이라는 타입가드이어야 합니다.

filter<S extends T>(predicate: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[];
filter(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T[];
    

타입 가드는 i의 타입이 아니라 filtered2의 타입을 정해주는 겁니다.

CJW님의 프로필

CJW

질문자

2023.03.06

그럼 predicate 에서의 i is string 도 i 의 타입이 아닌 리턴값에 대한 predicate의 타입을 지정해준건가요..?

네 맞습니다. return값들이 string이라는 걸 알려준 겁니다.