type transaction = {
uid: string,
paymentMode : string,
}
I want to get key name from type for e.g.
function getFieldName(input) {
returns a string with key name
}
const tran : transaction = {}
getKeyName(tran.paymentMode) returns 'paymentMode'
I read many articles and tried some solutions, so I understand we will at least need to create object for that type which is fine.
I want to do this because key name of a type is required and I also want to keep auto-complete for key name when we type something like obj.key
to avoid mistakes.
I know, I can create a separate object from type with constant key, value pair. I want to avoid this, because then we will need to change same thing at 2 places whenever there is a change in type, which can be missed.
Edit:
I was looking for exactly this -
type Transaction = {
uid: string;
paymentMode: string;
};
function getFieldName <T extends object, K extends keyof T>(o: T, key: K): K {
return key;
}
const transaction: Transaction = {
uid: window.crypto.randomUUID(),
paymentMode: 'unknown',
};
getFieldName(transaction, 'uid'); // "uid"
getFieldName(transaction, 'paymentMode'); // "paymentMode"
getFieldName(transaction, 'asdf'); /*
~~~~~~
Argument of type '"asdf"' is not assignable to parameter of type 'keyof Transaction'.(2345) */
It is not possible to derive a string property name in JavaScript (or TypeScript) by passing a reference to the property value. JavaScript simply doesn't have this kind of meta-introspection capability at present.
It appears that your question is not just about type safety, but about DX/ergonomics. The above solution does require providing the property name, but the number of extra characters to type before getting the IntelliSense prompt is only 1 (2 if you consider whitespace):
// For: obj.prop:
// desired:
fn(obj.p_)
// 012^
// proposed:
fn(obj, 'p_')
// 01234^
// The closing quote is auto-inserted by IntelliSense, just like the closing parenthesis.