본문 바로가기

개발하자

유형 스크립트는 함수 본문에서 일반 유형을 사용할 수 있습니다

반응형

유형 스크립트는 함수 본문에서 일반 유형을 사용할 수 있습니다

나는 다음과 같은 기능 선언을 가지고 있다:

export const filterOptions: <OptionValueType>(
  options: OptionsArray<OptionValueType>,
  filterBy: string
) => OptionsArray<OptionValueType> = (options, filterBy) => {
  if (filterBy === "") {
    return [...options];
  } else {
    const filteredOptions: OptionsArray<OptionValueType> = [];
    // filter and return options

    return [...filteredOptions];
  }
};

하지만, typescript는 이 코드를 Error로 표시합니다. 함수 본문에서 제네릭 형식을 사용할 수 있습니까?

const filteredOptions: OptionsArray<OptionValueType> = [];
TS2304: Cannot find name 'OptionValueType'



본문에서 제네릭 형식 매개 변수를 사용할 수 있지만 제네릭 형식 매개 변수는 함수를 유지할 변수가 아닌 함수 구현에 있어야 합니다

export const filterOptions = <OptionValueType>(options: OptionsArray<OptionValueType>, filterBy: string) : OptionsArray<OptionValueType> => {
    if (filterBy === '') {
        return [...options];
    } else {
        const filteredOptions: OptionsArray<OptionValueType> = [];
        // filter and return options


        return [...filteredOptions];
    }
};

반응형