shadeglare shadeglare - 1 year ago 161
TypeScript Question

Safe way to extract property names in TypeScript

I'm looking for a way to get an object property name with typechecking that allows to catch possible regressions after refactoring.

Here's an example: the component where I have to pass the property names as strings and it will be broken if I'll try to change the property names in the model.

interface User {
name: string;
email: string;

class View extends React.Component<any, User> {

constructor() {
this.state = { name: "name", email: "email" };

private onChange = (e: React.FormEvent) => {
let target = as HTMLInputElement;
this.state[] = target.value;

public render() {
return (
<input type="submit" value="Send" />

I'd appreciate if there's any nice solution to solve this issue.

Answer Source

Right now there's not really a great way of doing this, but there are currently some open suggestions on github (See #1579, #394, and #1003).

What you can do, is what's shown in this answer—wrap referencing the property in a function, convert the function to a string, then extract the property name out of the string.

Here's a function to do that:

function getPropertyName(propertyFunction: Function) {
    return /\.([^\.;]+);?\s*\}$/.exec(propertyFunction.toString())[1];

Then use it like so:

// nameProperty will hold "name"
const nameProperty = getPropertyName(() =>;

This might not work depending on how the code is minified so just watch out for that.


It's safer to do this at compile time. I wrote ts-nameof so this is possible:

nameof<User>(s =>;

Compiles to:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download