'Create union literal type from key values
The TableData
type has the same properties as the return type of the following function
const createTableData = (cod: string, promo: string, type: string) => ({
__typename: "TableData",
code: cod,
promo: promo,
type: type
})
type TableData = ReturnType<typeof createTableData>
I need to create a store dict which keys should be the same values as the code
key of TableData
. In other words I'm trying to create a type of the union literals of TableData["code"]
without success, for example
type SampleCode = "1234" | "1235" | "7631" | "4012"
type CodeTableData = SampleCode
class TableDataMock {
private store: Record<CodeTableData, TableData | undefined> = {
1234: undefined,
1235: undefined,
7631: undefined,
4012: undefined
}
}
As you can see the store
keys will be the future values of the TableData["code"]
but in my example the SampleCode
type has already been initialized with prior values.
EDIT:
The end result should look like this
const createTableData = (cod: string, promo: string, type: string) => ({
__typename: "TableData",
code: "123",
promo: promo,
type: type
})
type TableDataStore = {[C in ReturnType<typeof createTableData>["code"]]: undefined}
class TableDataMock {
private store: TableDataStore = {"123": undefined, "234": undefined}
^^^^
this should not be valid
}
The only valid keys of TableDataStore
should be 123
. Besides this example I need that the keys of TableDataStore
should be the future values of the code
property of TableData
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|