从模板中排除属性

时间:2018-08-01 07:47:48

标签: typescript

我有这段代码,可以在其中从接口中排除属性

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>

interface MyType {
  id: string
  timeout: number
  delta: number
}

let value: Omit<MyType, 'id'> = {
  timeout: 10,
  delta: 5,
}

可以,但是我不能从通用类型中排除该属性,如下所示:

function foo<T>(x: T) {
  let value: Omit<T, 'id'> = {
    timeout: 10,
    delta: 5,
  }
}
foo<MyType>({ timeout: 10, delta: 5 })

现在我收到错误消息Type '"id"' does not satisfy the constraint 'keyof T',我在做什么错了?

1 个答案:

答案 0 :(得分:1)

这是因为如果类型id word nth_word id word nth_word phrase_part -- ------------ -------- -- ------------ -------- ------------------------------------------------------------------------- 1 Need 1 1 Need 1 {"Need"} 1 Need 1 1 a 2 {"Need","a"} 1 Need 1 1 baby 3 {"Need","a","baby"} 1 Need 1 1 sitter 4 {"Need","a","baby","sitter"} 1 Need 1 1 for 5 {"Need","a","baby","sitter","for"} 1 Need 1 1 casual 6 {"Need","a","baby","sitter","for","casual"} 1 Need 1 1 sitting 7 {"Need","a","baby","sitter","for","casual","sitting"} 1 a 2 1 a 2 {"a"} 1 a 2 1 baby 3 {"a","baby"} 1 a 2 1 sitter 4 {"a","baby","sitter"} 实际上具有属性T,则编译器不能仅基于函数声明进行检查。我们可以添加一个约束来告诉编译器将传递的内容将具有id属性:

id

您会注意到,我没有使用对象常量初始化函数内的function foo<T extends { id: string }>(x: Omit<T, 'id'>) { let value: Omit<T, 'id'> = x; } foo<MyType>({ timeout: 10, delta: 5 }) 变量,这是因为如果您不知道完整类型,就无法创建对象常量。我们对value所了解的只是具有和T属性,对于其他id具有的属性,它们具有什么类型以及是否需要它们,我们一无所知。

如果您确实需要在函数内部初始化通用类型的变量,则唯一的(不安全)方法是使用类型声明:

T