I am wondering, if it is possible to to add a prefix or suffix to a TypeScript type which uses an array of strings as its keys.
type First = {
one: string
two: string
}
type Second = keyof First
type Third = {
[S in Second]: any
}
With this approach Third accepts the attributes one
& two
with any type. Which is amazing, as I only need to change the first type in order to have the others also updated.
Now I want a fourth type which is exactly the same as Third
but I want to add a prefix to the keys. Like a dollar sign or something.
Desired result:
type Fourth = {
$one: any
$two: any
}
I could just hard code it but than I would have to adjust the Fourth type if the First type has been changed.
Thank you.
keyof is a keyword in TypeScript which is used to extract the key type from an object type.
In TypeScript, an interface is an abstract type that tells the compiler which property names a given object can have. TypeScript creates implicit interfaces when you define an object with properties. It starts by looking at the object's property name and data type using TypeScript's type inference abilities.
A mapped type is a generic type which uses a union of PropertyKey s (frequently created via a keyof ) to iterate through keys to create a type: type OptionsFlags < Type > = { [ Property in keyof Type ]: boolean; };
Thus we had the “I” prefix for interfaces but not for types. But in the end, the “type” and the “interface” really can be used the same way and the differentiation is completely wasted.
Many files are in a folder, and you must add a prefix or suffix to all file names. Going through them one by one in File Explorer and adding a prefix or suffix is time-consuming. An excellent way to add prefixes and suffixes to multiple file names is with PowerShell.
Now, at the end of the day, once you understand that you don’t need “I” as a prefix and why you don’t need it, if it is in your coding standards and you have lots of existing code or others think about “I” all day, it’s okay to roll with it.
But in the end, the “type” and the “interface” really can be used the same way and the differentiation is completely wasted. The point is that in your code, you don’t care if it is an Interface or not, what you care about is that it is a type (not the keyword “type” but just the generic concept, “type”).
TS 4.1 has support for easy key remapping using template literal types:
type First = {
one: string
two: string
}
type Fourth = {
[K in keyof First as `$${K}`]: any
}
If you wanted to use the original type associated with each key instead of any
(if you're using TS, you should want to avoid any
when possible, after all!), replace
: any
with
: First[K]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With