TypeScript:如何使用映射类型推断数组项类型

时间:2017-09-20 21:36:44

标签: typescript types

我有一个问题,如何通过映射类型获取数组项类型 例如,当我使用arrayStr方法时,我可以推断出数组项的类型,但是如何在class One<T> { constructor( data: T ) { } array<R>(getter: ((obj: T) => R[])): Two<R> { return null; } arrayStr<K extends keyof T, R>(name: K, idField: keyof R): Two<R> { return null; } } class Two<T> { getItem(): T { return null; } getAsArray(): T[] { return []; } } const data = { a: [{ q: 1 }, { q: 2 }] }; const one = new One(data); const a = one.array(p => p.a); const aValue = a.getItem().q; const oneStr = new One(data); const aStre = oneStr.arrayStr('a'); const aStrValue = aStre.getItem().q; const oneStrId = new One(data); const aStrId = oneStrId.arrayStr('a', 'q'); const aStrValueId = aStre.getItem().q; 方法中进行推断?为什么在这个例子中aStrId有类型&#39;从不&#39;

Sandbox

public class ExceptionHandlerFilter extends OncePerRequestFilter {
    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            filterChain.doFilter(request, response);

        } catch (JwtException e) {
            setErrorResponse(HttpStatus.BAD_REQUEST, response, e);
            e.printStackTrace();
        } catch (RuntimeException e) {
            e.printStackTrace();
            setErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, response, e);
        }
    }

    public void setErrorResponse(HttpStatus status, HttpServletResponse response, Throwable ex){
        response.setStatus(status.value());
        response.setContentType("application/json");
        // A class used for errors
        ApiError apiError = new ApiError(status, ex);
        try {
            String json = apiError.convertToJson();
            System.out.println(json);
            response.getWriter().write(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

1 个答案:

答案 0 :(得分:0)

我在TypeScript Gitter link得到了答案。 这将有效:

arrayStr<K extends keyof T, R, E>(this: One<{[k in K]: R[] | E}>, name: K): Two<R> {