Issue
I have a constant similar to this in my project
Note: I am using typescript version 4.8.2
export const test = [
{ key: 'gdsfg', value: 'gsdf' },
{ key: 'ofadwned', value: 'gsdfgs' },
]; // type of test is -> const test: { key: string; value: string;}[]
If I use as const
at the end of constant I get the following type which I am expecting
export const test = [
{ key: 'gdsfg', value: 'gsdf' },
{ key: 'ofadwned', value: 'gsdfgs' },
] as const; // type of test is -> const test: readonly [{readonly key: "gdsfg";readonly value: "gsdf";}, {readonly key: "ofadwned";readonly value: "gsdfgs";}]
As this const is used in multiple places in the project, I can't add as const
at the end of it an break the existing type system
Is there any other way in typescript to achieve this? something like
type expectedType = (typeof test) as const; // This is currently not possible in Typescript
// I want expectedType is of type -> readonly [{readonly key: "gdsfg";readonly value: "gsdf";}, {readonly key: "ofadwned";readonly value: "gsdfgs";}]
My use-case is not only checking the type but also extracting multiple types from the const which is not possible with type annotation.
Code sample:
// Legacy code start >>>>>>>>>>>>>>>>
type KeyValue = {key: string, value: string};
// These constants are used in multiple places with this type
// I can't change these as it breaks ifExists function constant type
const constants1: KeyValue[] = [
{ key: 'key1', value: 'gsdf' },
{ key: 'key2', value: 'gsdfgs' },
];
const constants2: KeyValue[] = [
{ key: 'key3', value: 'gsdghjkghjngff' },
{ key: 'key4', value: 'jfgjgrhr' },
{ key: 'key5', value: 'erqwe' },
];
// Just added simple function to simulate the behaviour but acutal function has more complex types and structure
// I can't change this
const ifExists = (checkValue: string, constant: KeyValue[]) => {
return constant.find(c => c.key === checkValue)
}
const check = ifExists('afsd', constants1)
// Legacy code ends >>>>>>>>>>>>>>>>>>>
// Code I have control
type CustomType = {
property1: string,
validKey: 'key1' | 'key2' | 'key3' | 'key4' | 'key5' // keys from constant1 and constant2
// This is the type I am expecting to be dynamic, I don't want to update this type when new constant is added or existing one is updated
}
// api response
const responseFromBackend: CustomType = {
property1: 'dfasdfasf',
validKey: 'key5'
}
// My question - can I get the literal type of a const without actually using as const, something like follows
// I want CustomConstant1 to be of type 'key1' | 'key2'
type CustomConstant1 = ((typeof constants1) as const)[number]['key'] // This doesn't work
// I want to have type validKey in CustomType dynamically
Please refer the code sample link.
Solution
This can be achieved with satisfies
keyword as pointed out by the @jcalz in the comments.
Note: satisfies
keyword is added to Typescript in v4.9
Answered By - Ravi Teja Vattem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.