首页 > 解决方案 > 为什么`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

标签: typescript

解决方案


您实际上并没有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>

游乐场链接


推荐阅读