小编Ste*_*pan的帖子

一种禁用泛型中的“类型参数推断”的方法?

我希望为泛型提供默认值将优先于类型推断,但事实并非如此:

// placeholder for a real express response.send
const sendResponse =  (x) => console.log(x);

function sendResult<T = never>(send: any, result: T) {
  send(result);
}

// I want to use this always with a type
type Num = { x: number };
sendResult<Num>(sendResponse, { x: 1 });
sendResult<Num>(sendResponse, { x: 'sss' }); // correctly showing error

// When I don't supply type, I'd like an error.
// But, T gets inferred instead of defaulting to never... so, no error :-(
sendResult(sendResponse, …
Run Code Online (Sandbox Code Playgroud)

typescript

4
推荐指数
1
解决办法
138
查看次数

标签 统计

typescript ×1