首页 > 解决方案 > 通用打字稿类型定义,包括。原始类型

问题描述

只是一个简单的问题。我需要一个对某种类型通用的类TT应该是 type 的一个string或某个子类Bar。但是,如果我按如下方式编写,则T解析为T extends Baror T extends string

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

什么是正确的写法以便T解析为T extends Baror string

标签: typescriptgenericstypes

解决方案


拥有类型T extends string允许这样做(基本上限制运行方法以使用特定的字符串文字类型调用)

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

推荐阅读