typescript - 为什么`semantic error TS2344: Type '"ptn3"' 不满足约束 '"ptn1" | “ptn2”'。`
问题描述
我正在使用 TypeScript 3.8.3。
我想指定接口键并获取类型信息,所以我写了以下代码。
interface T1 {
ptn1 : string
ptn2 : number
}
type Factory<N extends keyof T1, T extends T1 = T1> = T1[N]
type F1 = Factory<'ptn1'> // F1 type is "string"
好的,它有效。
然后,我想扩展T1
类型以便能够使用它,所以我将其更改如下。
export interface T1 {
ptn1 : string
ptn2 : number
}
export type Factory<N extends keyof T1, T extends T1 = T1> = T1[N]
// OTHER FILE --------------
import { T1, Factory } from './above_code.ts'
type F1 = Factory<'ptn1'> // F1 type is "string"
interface T2 extends T1 {
ptn3: Object
}
type T2keys = keyof T2 // T2keys = "ptn3" | "ptn1" | "ptn2"
type F2 = Factory<'ptn2'> // F2 type is "number"
但是下面的代码会输出错误。
// A continuation of the code above..
type F3 = Factory<'ptn3', T2> // semantic error TS2344: Type '"ptn3"' does not satisfy the constraint '"ptn1" | "ptn2"'.
为什么会出现 TS2344 错误?
我怎样才能写成type 3 = Factory<'ptn3', T2>
一个Object
?
解决方案
您实际上并没有T
在类型内部使用Factory
:
export type Factory<N extends keyof T, T extends T1 = T1> = T[N]
export interface T1 {
ptn1 : string
ptn2 : number
}
type F1 = Factory<'ptn1'> // F1 type is "string"
interface T2 extends T1 {
ptn3: Object
}
type F2 = Factory<'ptn2'> // F2 type is "number"
type F3 = Factory<'ptn3', T2>
推荐阅读
- r - R:获取目录中所有文件的短文件名(文件名)列表
- regex - 用于在 .lua 文件中捕获“/*...*/”样式注释的正则表达式
- c++ - 为什么 sizeof 数组(字符串类型)是 24 字节,带有单个空格元素?
- matplotlib - 使用图像时如何删除matplotlib子图中的所有填充
- react-native - 将 expo 应用程序发布到 App Store/Google Play 商店
- react-native - 在 React-Native 中使用 Twilio 发送短信
- jenkins - 有没有办法我们可以根据构建名称下载 jenkins 中的存档工件(创建格式化的版本号)
- java - 如何在 Play 框架中的 Java 代码中修复“不明确的方法调用”
- javascript - 尝试打印页面时如何隐藏导航栏
- python - 递归算法的时间复杂度