如何存在参数类型时如何添加更多类型

时间:2018-06-05 10:27:14

标签: typescript typescript-typings

当我想在参数存在时扩展更多类型时,我有问题,如下面的代码。

const animalTalk = {
  talk: (name: 'dog' | 'cat') => { // This code not allow for update
    console.log(name)
  },
}
animalTalk.talk = (name ) => { // << I would like to extends more 'mouse' in 'name'
  if (name === 'mouse') {

  }
}
我该如何解决这个问题? 感谢

1 个答案:

答案 0 :(得分:1)

您可以明确声明第二种类型的参数:

const animalTalk = {
    talk: (name: 'dog' | 'cat') => { // This code not allow for update
        console.log(name)
    },
}
animalTalk.talk = (name: 'dog' | 'cat' | "mouse") => { 
    if (name === 'mouse') {

    }
}

如果您不想复制公共部分,我们可以使用条件类型来提取参数(在第一种情况下,但您可以为其他位置创建类似的类型)

type FirstArgument<T> = T extends (p: infer A)=> any? A : never;
animalTalk.talk = (name: FirstArgument<typeof animalTalk['talk']> | "mouse") => { 
    if (name === 'mouse') {

    }
}