admin管理员组文章数量:1122832
In typescript,for an object,I can restrict its key to a specified range and value to a specified range. Can I restrict the type of a certain key to a certain value?
for example, I have this
interface ValueType1 {
key1: string,
key2: string,
}
interface ValueType2 {
key3: number,
key4: number,
}
type KeyType = 'value1' | 'value2';
const map: {[key in KeyType]: ValueType1 | ValueType2} = {
'value1': {
key1: '123',
key2: '123'
},
'value2': {
key3: 123,
key4: 123,
}
}
If I want to restrict when key = 'value1', the type of Value must be ValueType1, so as the value2. Is this possible?
In typescript,for an object,I can restrict its key to a specified range and value to a specified range. Can I restrict the type of a certain key to a certain value?
for example, I have this
interface ValueType1 {
key1: string,
key2: string,
}
interface ValueType2 {
key3: number,
key4: number,
}
type KeyType = 'value1' | 'value2';
const map: {[key in KeyType]: ValueType1 | ValueType2} = {
'value1': {
key1: '123',
key2: '123'
},
'value2': {
key3: 123,
key4: 123,
}
}
If I want to restrict when key = 'value1', the type of Value must be ValueType1, so as the value2. Is this possible?
Share Improve this question edited Nov 22, 2024 at 6:09 DarkBee 15.8k8 gold badges69 silver badges110 bronze badges asked Nov 22, 2024 at 3:55 Cody ZCody Z 233 bronze badges 1 |1 Answer
Reset to default 0Just map the keys and types directly. Also I recommend using as const satisfies
in the most cases since it will give you more precise/narrow types which could be a benefit later:
Playground
type ValueMap = {
value1: ValueType1,
value2: ValueType2
}
const map: ValueMap = {
'value1': {
key1: '123',
key2: '123'
},
'value2': {
key3: 123,
key4: 123,
}
}
const constMap = {
'value1': {
key1: '123',
key2: '123'
},
'value2': {
key3: 123,
key4: 123,
}
} as const satisfies ValueMap
本文标签: typescriptIs it possible to restrict the type of a certain key to a certain valueStack Overflow
版权声明:本文标题:typescript - Is it possible to restrict the type of a certain key to a certain value? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736305731a1932696.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
value1
maps toValueType1
andvalue2
maps toValueType2
come from, if it's not hardcoded? (also: what does this question have to do with syntactic sugar?) – jcalz Commented Nov 22, 2024 at 3:58