typescript - 通用打字稿类型定义,包括。原始类型
问题描述
只是一个简单的问题。我需要一个对某种类型通用的类T
。T
应该是 type 的一个string
或某个子类Bar
。但是,如果我按如下方式编写,则T
解析为T extends Bar
or T extends string
。
class Foo<T extends Bar | string> {
run(data: T): void { ... }
}
什么是正确的写法以便T
解析为T extends Bar
or string
?
解决方案
拥有类型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
推荐阅读
- c - 情况 3:如果 n 是 3 和 5 的倍数
- javascript - 获取数组的平均数,如果其中一个在 JS 上为 -1,则中断
- c# - aspNetHidden div 未根据客户端提供服务
- javascript - Android 的 BuiltInZoom 在混合应用程序中不起作用
- c# - 在这种情况下,C# 还会调用 Dispose 吗?
- javascript - 如何暂停javascript for循环(动画冒泡排序)?
- javascript - 角度 ngClass 指令未应用
- snowflake-cloud-data-platform - Snowflake中的工作表、错误表和日志表?
- javascript - Netsuite SuiteScript:用于从自定义记录和默认字段打开新事务的按钮
- javascript - 您将如何使用 Codemirror 文档来获得多个编辑器?