从解构对象中的rest参数输入const

问题描述

我正在尝试显式键入一个常量,该常量是使用解构对象中的其余参数创建的。我可以看到打字稿可以推断它将具有源对象类型的所有属性,减去我为其创建单独常量的任何属性。但是,我有一个预定义的类型,我特别想将其用于我的新常量。这可能吗?

interface Animal {
    name: string,species: string,legs: number,tail: boolean,alive: boolean,}

// say we kNow an animal is alive and therefore want a type without this property
// (yes,we Could extend Animal with alive: true,but this a contrived example,go with it)
type LivingAnimal = Omit<Animal,'alive'>

// dave is an Animal,but we want a LivingAnimal type from him,which omits the 'alive' property
const dave: Animal = {
    name: 'Dave',species: 'lizard',legs: 4,tail: true,alive: true,}

// with object destructuring,I can infer that alive is a boolean and daveAnimal is the same type as LivingAnimal (ie has all the same props as Animal except alive)
// But what I actually *want* to achieve is to type daveAnimal specifically as LivingAnimal
const {alive,...daveAnimal} = dave;

// but when I try and do this,it fails
const {alive2,...daveAnimal2}: {alive2: string,...daveAnimal2: LivingAnimal} = dave;

// so is there a way of specifying a predefined type for the animal const,created with a rest param in a destructured object?

这是code in the typescript playground

我已经做了一些谷歌搜索并阅读了诸如 this one 之类的文章和诸如 this one 之类的其他 SO 问题,但它们并没有完全涵盖我对其余参数的使用,或者至少没有以我的方式明白了。

我希望我已经充分解释了我想要实现的目标。这不是很重要 - 在实践中我可以使用我已经拥有的东西,更多的是为了整洁和提高我的理解。感谢您分享的任何智慧。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...