3 ms·
It's pretty easy to do in Typescript and loses no type safety (without needing to assert or cast anything) type T = { [k: string]: number }; const
by mssundaram 6y ago
It's pretty easy to do in Typescript and loses no type safety (without needing to assert or cast anything)
type T = { [k: string]: number };
const t: T = {
one: 1,
two: 2,
three: 3,
};
const makeUpperCaseKeys = (v: T): T => {
const keys = Object.keys(v);
return keys.reduce((p, c) => {
const key = c.charAt(0).toUpperCase() + c.slice(1);
return { ...p, [key]: v[c] };
}, {});
};
console.log(makeUpperCaseKeys(t));
// {
// One: 1,
// Two: 2,
// Three: 3
// }
- dack 6y agoThat's great! Are you making the argument that I won't be able to find an example where doing some transform in a type-safe way is awkward in TypeScript, or just that this one example can be done in TypeScript? By the way, my example was meant to be more like User -> User where there are some string values and some other types of value. You want to do the transformation in a generic way, but still have the type-safe object come out the other end with all the expected keys.
- deleted 6y ago[deleted]
- sbergot 6y agoYou can try this with typescript 4.1 : interface User { name: string; age: number; } type CapitalizeProperties<T> = { [Property in keyof T as Capitalize<string & Property>]: T[Property]; }; type CUser = CapitalizeProperties<User>; var c : CUser = { Age: 17, Name: "john" } You can check that the autocompletion works on the c variable. https://www.typescriptlang.org/play?ssl=1&ssc=1&pln=15&pc=2#code/JYOwLgpgTgZghgYwgAgKoGdrIN4ChkHIhwC2EAXMumFKAOYDc+hcdFRAriQEbRMC+uXGACeABxQBhOGOBg4AG2AAvCAAUoAewlQwwCOgA8AFQB8yALw5mAbQ3boo5KGQBrCCM0xkx5HHTI0rLySqqG1LQgdMgAZMj2OqKmALqUxnZaiSLJAkzC4lIYWFZBcooq6pmO+kZFUKZ5AG5wUMgIyJSSdZbWyACCbJQAjADsADT4AHKk7ABEAFaaABYgs7j8QA https://www.typescriptlang.org/play?ssl=1&ssc=1&pln=15&pc=2#...
- deleted 6y ago[deleted]