TypeScript函数不从超级接口推断通用参数

时间:2018-05-23 00:22:43

标签: typescript generics

这最容易用代码来解释:

interface ApiRequest<T> {}
interface SomeRequest extends ApiRequest<string> {
    value: string;
}

function sendRequest<
    TRequest extends ApiRequest<TResponse>,
    TResponse
>(
    request: TRequest
): TResponse {
    return null as TResponse;
}

const x = sendRequest({ value: "a value" } as SomeRequest);

// Type of x is inferred as {} rather than string
x.length;

sendRequest函数应该根据SomeRequest使用ApiRequest<T>扩展string的事实来推断TResponse,但它并不是。相反,它推断{}并且没有错误。

如何在不明确声明类型参数的情况下执行此操作?

1 个答案:

答案 0 :(得分:3)

不要制作比你更多的通用类型参数。如果类型参数仅在输入位置出现一次(即不在返回类型中而不是在两个不同的参数中),则将其减少为非约束版本:

        foreach (DataRow row in data.Rows)
        {

            ID = row["Mem_id"].ToString();
             Name = row["Mem_Name"].ToString();
             Email = row["Mem_Email"].ToString();
             Designation = row["Mem_Designation"].ToString();
             Depart = row["Mem_Dept"].ToString();
             Phone = row["Mem_Phone"].ToString();
             MemType = row["Mem_Type"].ToString();
             image = "<img width=100 height=100 src=/imagesz/" + row["Mem_Image"].ToString() + ">";

             tbl.Text = tbl.Text + "<tr><td>" + ID + "</td><td>" + Name + "</td><td>" + Email + "</td><td>" + Designation + "</td><td>" + Depart + "</td><td>" + Phone + "</td><td>" + MemType + "</td><td>" + image + "</td><td>I WANT TO ADD ASP.NET DELETE BUTTON HERE</td></tr>";


        }


    }

您还需要在function sendRequest<TResponse>(request: ApiRequest<TResponse>): TResponse { return null as TResponse; }

中的某处显示T
ApiRequest