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
  • 2 Uh, well you can define an interface that works that way, as shown in this playground link. But that's so obvious, I must be missing something. Presumably you are looking for something else, but what, exactly? Where does the information that value1 maps to ValueType1 and value2 maps to ValueType2 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
Add a comment  | 

1 Answer 1

Reset to default 0

Just 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