nameof in TypeScript


Keywords
nameof, typescript, transformer, custom-transformer, babel-plugin
License
MIT
Install
npm install ts-nameof@5.0.0

Documentation

ts-nameof

Build Status

nameof in TypeScript.

Monorepo for ts-nameof projects:

nameof transform

nameof(...)

nameof(console);
nameof(console.log);
nameof(console["warn"]);

Transforms to:

"console";
"log";
"warn";

nameof<T>()

nameof<MyInterface>();
nameof<Array<MyInterface>>();
nameof<MyNamespace.MyInnerInterface>();

Transforms to:

"MyInterface";
"Array";
"MyInnerInterface";

This is useful when working in the type domain.

nameof<T>(o => ...)

nameof<MyInterface>(o => o.prop);

Transforms to:

"prop";

nameof.full transform

nameof.full(...)

nameof.full(console.log);
nameof.full(window.alert.length, 1);
nameof.full(window.alert.length, 2);
nameof.full(window.alert.length, -1);
nameof.full(window.alert.length, -2);
nameof.full(window.alert.length, -3);

Transforms to:

"console.log";
"alert.length";
"length";
"length";
"alert.length";
"window.alert.length";

nameof.full<T>()

nameof.full<MyNamespace.MyInnerInterface>();
nameof.full<MyNamespace.MyInnerInterface>(1);
nameof.full<Array<MyInterface>>();

Transforms to:

"MyNamespace.MyInnerInterface";
"MyInnerInterface";
"Array";

nameof.full<T>(o => ...)

nameof.full<MyInterface>(o => o.prop.prop2);
nameof.full<MyInterface>(o => o.prop.prop2.prop3, 1);

Transforms to:

"prop.prop2";
"prop2.prop3";

nameof.interpolate(value)

Writing the following:

nameof.full(myObj.prop[i]);

...does not interpolate the node in the computed property.

"myObj.prop[i]";

If you want to interpolate the value then you can specify that explicitly with a nameof.interpolate function.

nameof.full(myObj.prop[nameof.interpolate(i)]);

Transforms to:

`myObj.prop[${i}]`;

nameof.toArray transform

Contributed by: @cecilyth

nameof.toArray(...)

nameof.toArray(myObject, otherObject);
nameof.toArray(obj.firstProp, obj.secondProp, otherObject, nameof.full(obj.other));

Transforms to:

["myObject", "otherObject"];
["firstProp", "secondProp", "otherObject", "obj.other"];

nameof.toArray<T>(o => [...])

nameof.toArray<MyType>(o => [o.firstProp, o.otherProp.secondProp, o.other]);
nameof.toArray<MyType>(o => [o.prop, nameof.full(o.myProp.otherProp, 1)]);

Transforms to:

["firstProp", "secondProp", "other"];
["prop", "myProp.otherProp"];

Other