“条件类型"不能使用真正的功能吗? [英] "Conditional types" won't work with real function?

查看:20
本文介绍了“条件类型"不能使用真正的功能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 https://www.typescriptlang.org/docs/handbook/2/conditional-types.html

我想知道为什么这不起作用?

I'm wondering why this won't work?

interface IdLabel {
  id: number
}

interface NameLabel {
  name: string
}

type NameOrId<T extends number | string> = T extends number
  ? IdLabel
  : NameLabel;

function createLabel<T extends number | string>(idOrName: T): NameOrId<T> {
  if (typeof idOrName === 'number') {
    return { id: 1 }
  } else {
    return { name: 'foo' }
  }
}

但是,这会起作用(这是文档给出的示例),但这完全没用,甚至不返回任何值...

However, this will work (which is the example given by the doc), but this is totally useless it even not returns any value...

function createLabel<T extends number | string>(idOrName: T): NameOrId<T> {
  throw "unimplemented";
}

条件类型是否仅适用于类型定义"...?

Does the conditional types only works with "type definition"..?

推荐答案

简短的回答是你不能.无法为未解析的条件类型(仍然依赖于自由泛型类型变量的条件类型)分配任何值.您唯一能做的就是使用类型断言.

The short a answer is you can't. No value will be assignable to an unresolved conditional type (a conditional type that still depends on a free generic type variable). The only thing you can do is use a type assertion.

来自:https://stackoverflow.com/a/52144866/12397250

所以你可以做的是:

function createLabel<T extends number | string>(idOrName: T): NameOrId<T> {
  if (typeof idOrName === 'number') {
    return { id: 1 } as NameOrId<T>
  } else {
    return { name: 'foo' } as NameOrId<T>
  }
}

2.重载方法

function createLabel<T extends number | string>(idOrName: T): NameOrId<T>;
function createLabel(idOrName: number | string): IdLabel | NameLabel {
  if (typeof idOrName === 'number') {
    return { id: 1 }
  } else {
    return { name: 'foo' }
  }
}

这篇关于“条件类型"不能使用真正的功能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆