繁体   English   中英

在传播结果上声明打字稿类型

[英]declare typescript type on spread results

我有这样的代码:

type myType = {
  key1: string,
  optKey?: boolean,
}

const obj = {
  key1: 'hi',
  key2: 'yes',
}

const { key2, ...typedObj } = obj
typedObj.optKey = true

现在打字稿抱怨: Property 'optKey' does not exist on type '{ key1: string; }' Property 'optKey' does not exist on type '{ key1: string; }'

我想告诉打字稿typedObj实际上是myType的一个实例。 有没有办法做到这一点,无论是在const spread 声明期间还是之后?

这有效:

typedObj2 = typedObj as myType

但是还有另一种没有临时无类型变量的方法吗?

您首先需要定义您的obj ,这与myType有关

这是解决问题的示例。

type myType = {
  key1: string,
  optKey?: boolean,
}

const obj: myType & { key2: string } = {
  key1: 'hi',
  key2: 'yes',
}

const { key2, ...typedObj } = obj
typedObj.optKey = true

操场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM