【问题标题】:Is there a way to specifiy the base type of a generic function?有没有办法指定泛型函数的基本类型?
【发布时间】:2021-10-21 04:19:14
【问题描述】:

有没有办法将泛型类型T 指定为对象,即不是像数字或字符串这样的原始类型?

例如这个克隆函数应该只允许对象作为输入,因为它将解构o,将原型设置回原始对象的原型并返回。

export function clone<T>(o: T): T {
  return Object.setPrototypeOf({ ...o }, o.constructor.prototype);
}

linter 显示错误:

类型“T”上不存在属性“构造函数”

【问题讨论】:

  • function clone&lt;T extends object&gt;(o: T): T { ... } 小写o

标签: typescript typescript-typings typescript-generics


【解决方案1】:

The object type(注意小写的o)是专门为匹配“非原始”类型而引入的;也就是说,object 本质上是string | number | bigint | boolean | symbol | undefined | null 的补集。

Don't confuse it with Object(带有大写的O),它指的是可以像对象一样索引到的任何东西,本质上是undefined | null的补充。毕竟像"foo" 这样的字符串有一个明显的toUpperCase() 方法;当您调用"foo".toUpperCase() 时,它会将"foo" 包装在String 对象中。如果要排除 string 之类的原语,则需要 object 而不是 Object

无论如何,这意味着clone() 的调用签名应该是这样的:

export function clone<T extends object>(o: T): T {
  return Object.setPrototypeOf({ ...o }, o.constructor.prototype);
}

通过constraining 类型参数Tobject,您将只允许o 的非原始参数:

clone(new Date()); // okay
clone({ a: 1, b: 2 }); // okay
clone([1, 2, 3]); // okay
clone("oops"); // error
clone(123); // error
clone(false); // error
clone(Symbol("wha")); // error
clone(undefined); // error
clone(null); // error

Playground link to code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    相关资源
    最近更新 更多