通用打字稿类型定义,包括基本类型

时间:2020-09-14 07:06:44

标签: typescript generics types

一个简单的问题。我需要一个在某些类型T上通用的类。 T应该是stringBar类型的某个子类。但是,如果我将其编写如下,则T解析为T extends BarT extends string

class Foo<T extends Bar | string> {
    run(data: T): void { ... }
}

T解析为T extends Barstring的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

具有类型T extends string可以做到这一点(基本上限制了以特定字符串文字类型调用run方法)

type Bar = {
  a: string
}

class Foo<T extends Bar | string> {
  run(data: T): void {
    console.log(data)
  }
}

const fooBar = new Foo<'bar'>()
const fooString = new Foo<string>()

fooBar.run('bar') // compiles
fooBar.run('baz') // does not compile

fooString.run('bar') // compiles
fooString.run('baz') // compiles

如果您不希望使用此语义,则可以很好地输入以下内容


class Foo<T extends Bar> {
  run(data: T | string): void {
    console.log(data)
  }
}

const fooBar = new Foo()

fooBar.run('bar') // compiles
fooBar.run('baz') // compiles