0

我正在尝试显式键入一个 const,该 const 是使用解构对象中的 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?

这是打字稿游乐场中的代码

我已经进行了一些谷歌搜索并阅读了类似这篇文章和其他类似这篇文章的SO 问题,但它们并没有完全涵盖我对休息参数的使用,或者至少不是以我理解的方式。

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

4

0 回答 0