typescript - 如何在 TypeScript 类方法中有条件地提示布尔返回类型?
问题描述
在以下代码示例中,我的目标是:
- 让
obj.isX
当由 A 型构造true
时obj
- 让
obj.isX
当由 B 类构造false
时obj
type A = { x: true };
type B = { x: false };
type AorB = A | B;
class MyClass<Input extends AorB> {
_input: Input;
constructor(input: Input) {
this._input = input;
}
isX(): Input extends A ? true : false {
return this._input.x;
}
}
但我得到了Type 'boolean' is not assignable to type 'Input extends A ? true : false'.(2322)
打字稿游乐场:
解决方案
推荐阅读
- cors - CORS Preflight 请求是否包含请求的标头?
- java - 如何根据 Java 中另一个列表中的项目从列表的子集中获取项目列表?
- arrays - 使用 Powershell 生成 PDF
- apache-spark - Spark 自定义模式和 jdbc 无法正确呈现数据
- python - 有没有办法将两个变量与存储为字符串的比较器进行比较
- java - 如何更改速度模板中的小数点分隔符?
- node.js - 在 Elastic Beanstalk AWS 中为 nodeJs 应用程序提供静态文件
- apache-spark - 原因:org.apache.spark.sql.catalyst.parser.ParseException: DataType void is not supported.(line 1, pos 0)
- c# - 我有一个自定义文本框,我已经设置了预定义的值,即文本框的 (value = "sa") 现在字段不可编辑 c#?
- javascript - 有没有办法在警报框中显示对象的输入值?