【发布时间】:2020-04-11 00:55:39
【问题描述】:
我使用的是 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?
【问题讨论】:
标签: typescript