programing

TypeScript 화살표 함수에서 반환 유형 지정

nasanasas 2020. 10. 17. 10:35
반응형

TypeScript 화살표 함수에서 반환 유형 지정


저는 React와 Redux를 사용하고 있으며 인터페이스로 지정된 액션 유형을 가지고 있으므로 리듀서는 향상된 유형 안전성을 위해 태그 된 공용체 유형을 활용할 수 있습니다.

따라서 다음과 같은 유형 선언이 있습니다.

interface AddTodoAction {
    type: "ADD_TODO",
    text: string
};

interface DeleteTodoAction {
    type: "DELETE_TODO",
    id: number
}

type TodoAction = AddTodoAction | DeleteTodoAction

이러한 액션을 만드는 도우미 함수를 만들고 싶은데 화살표 함수를 사용하는 편입니다. 내가 이것을 쓰면 :

export const addTodo1 = (text: string) => ({
    type: "ADD_TODO",
    text
});

컴파일러는 AddTodoAction반환 유형이 명시 적으로 지정되지 않았기 때문에 이것이 유효한지 확인하는 데 도움을 줄 수 없습니다 . 다음과 같이 명시 적으로 반환 유형을 지정할 수 있습니다.

export const addTodo2: (text: string) => AddTodoAction = (text: string) => ({
    type: "ADD_TODO",
    text
})

그러나 이것은 내 함수 인수를 두 번 지정해야하므로 장황하고 읽기가 더 어렵습니다.

화살표 표기법을 사용할 때 반환 유형을 명시 적으로 지정할 수있는 방법이 있습니까?

나는 이것을 시도해 보았다.

export const addTodo3 = (text: string) => <AddTodoAction>({
    type: "ADD_TODO",
    text
})

이 경우 컴파일러는 이제 반환 형식을 다음과 같이 추론 AddTodoAction하지만 반환 하는 개체에 적절한 필드가 모두 있는지 확인하지 않습니다.

다른 함수 구문으로 전환하여이 문제를 해결할 수 있습니다.

export const addTodo4 = function(text: string): AddTodoAction {
    return {
        type: "ADD_TODO",
        text
    }
}

export function addTodo5(text: string): AddTodoAction {
    return {
        type: "ADD_TODO",
        text
    }
}

이 방법 중 하나를 사용하면 컴파일러가 올바른 반환 유형을 사용하고 모든 필드를 적절하게 설정하도록 강제 할 수 있지만, 더 장황하고 this함수에서 ' '가 처리 되는 방식을 변경합니다 (문제가되지 않을 수 있음). 나는 추측한다.)

이를 수행하는 가장 좋은 방법에 대한 조언이 있습니까?


먼저 원래 질문에서 다음 표기법을 고려하십시오.

export const addTodo3 = (text: string) => <AddTodoAction>({
    type: "ADD_TODO",
    text
})

Using this notation, you typecast the returned object to the type AddTodoAction. However, the function's declared return type is still undefined (and the compiler will implicitly assume any as return type).

Use the following notation instead:

export const addTodo3 = (text: string): AddTodoAction => ({
    type: "ADD_TODO",
    text: text
})

In this case, omitting a required property will yield the expected compiler error. For example, omitting the text property will generate the following (desired) error:

Type '{ type: "ADD_TODO"; }' is not assignable to type 'TodoAction'.
  Type '{ type: "ADD_TODO"; }' is not assignable to type 'DeleteTodoAction'.
    Types of property 'type' are incompatible.
      Type '"ADD_TODO"' is not assignable to type '"DELETE_TODO"'.

Also see the playground example.


I think your best bet is to create an interface for your function which has the right types, then you only need to specify that type, not all the nested types of your interface:

interface AddTodoAction {
    type: "ADD_TODO",
    text: string
};

interface AddTodoActionCreator {
    (text: string): AddTodoAction;
};

export const addTodo: AddTodoActionCreator = (text) => ({
    type: "ADD_TODO",
    text
});

Update: How to do this with types

export interface GeneralAction<T> {
    type: string;
    payload: T;
}

export interface GeneralActionCreator<T> {
    (payload: T): GeneralAction<T>;
}

export const SAVE_EVENT = 'SAVE_EVENT';

export const SaveEvent: GeneralActionCreator<UserEvent> = (payload) => { return {type: SAVE_EVENT, payload}; };

참고URL : https://stackoverflow.com/questions/40270393/specify-return-type-in-typescript-arrow-function

반응형