【问题标题】:why `semantic error TS2344: Type '"ptn3"' does not satisfy the constraint '"ptn1" | "ptn2"'.`为什么`语义错误TS2344:类型'"ptn3"'不满足约束'"ptn1" | “ptn2”'。`
【发布时间】: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&lt;'ptn3', T2&gt; 写成Object

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您实际上并没有在 Factory 类型中使用 T

    
    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>
    

    Playground Link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-12
      • 2019-09-12
      • 2019-09-19
      • 2021-03-16
      • 2021-01-28
      • 1970-01-01
      • 2021-03-02
      • 2020-10-25
      相关资源
      最近更新 更多