i have code like so:
type myType = {
key1: string,
optKey?: boolean,
}
const obj = {
key1: 'hi',
key2: 'yes',
}
const { key2, ...typedObj } = obj
typedObj.optKey = true
now typescript complains: Property 'optKey' does not exist on type '{ key1: string; }'
Property 'optKey' does not exist on type '{ key1: string; }'
i'd like to inform typescript that typedObj
is in fact an instance of myType
. is there a way to do this, either during the const
spread declaration, or afterwards?
this works:
typedObj2 = typedObj as myType
but is there another way without a temporary untyped variable?
You need to define your obj
at first, something that has to do with myType
Here is an example that fixes the problem.
type myType = {
key1: string,
optKey?: boolean,
}
const obj: myType & { key2: string } = {
key1: 'hi',
key2: 'yes',
}
const { key2, ...typedObj } = obj
typedObj.optKey = true
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.