如何在TypeScript构造函数中推断条件泛型类型?
如何在TypeScript构造函数中推断条件泛型类型?
在以下示例中,TypeScript无法自动推断new Hash({ a: 1, b: 2 })的类型,必须显式指定new Hash<string, number>({ a: 1, b: 2 })才能正常运行。
class Hash<K, V> { _impl = new Map<K, V>() constructor() constructor(items: (K extends string ? { [key: string]: V } | undefined : undefined)) constructor(items?: Record<string, V>) { if (items) for (let k in items) this._impl.set(k as any, items[k]) } set(k: K, v: V) {} } const h1 = new Hash<string, number>({ a: 1, b: 2 }) // 正常工作 h1.set('a', 1) const h2 = new Hash({ a: 1, b: 2 }) // 无法推断类型,报错 h2.set('a', 1) const h3 = new Hash<number, number>() // 正常工作 const h4 = new Hash<string, number>() // 正常工作
补充说明:
@jcalz提出了一种借助辅助函数的可行解决方案,这里保留原问题,探索是否存在其他解决思路。
function H<V>(items: Record<string, V>): Hash<string, V> function H<K, V>(items: [K, V][]): Hash<K, V> function H<K, V>(items: Record<string, V> | [K, V][]): Hash<any, V> { if (items instanceof Array) return new Hash(items) else return new Hash(items) } H({ a: 1, b: 2 }) H([[1, 1], [2, 2]])
内容的提问来源于stack exchange,提问作者Alex Craft
相关产品推荐
相关产品推荐

