In TypeScript 4.1, is it possible to get a class name or a function name as literal string type?
e.g.
class Foo { }
type Tpl = `${Foo["name"]}_${"a" | "b" | "c"}`; // error
// should be
// "Foo_a" | "Foo_b" | "Foo_c"
Edit (extended use cases)
Since the first example is not enough explicit and could be resolved with "Foo_a" | "Foo_b" | "Foo_c"
as type, here another ones.
class Animal { /* code */ }
class Dog extends Animal { }
class Cat extends Animal { }
class Duck extends Animal { }
// also, someone outside my original code decide to implement another
// animal, and so on. (for example, "MyAwesomeChimera")
class MyAwesomeChimera extends Animal { }
// "try" to extract name
type GetName<T extends Function> = T["name"]; // return string for now
// the goal here is, for whatever reasons,
// to use template literal to pre validate a query string
// that uses class names
type ClassQueryTemplate<T extends Array<typeof Animal>> =
`CQT ${ GetName<T[number]> }---CALL()`;
function querier<T extends Array<typeof Animal>>(...animals: T):
(query: ClassQueryTemplate<T>) => void { /* code */ return null as any; }
// impl & usage
const query = querier(
Dog,
Duck,
MyAwesomeChimera,
Cat,
);
// tests
query(`CQT Duck---CALL()`); // ok, but no autocomplete
query(`CQT Dog---CALL()`); // ok, but no autocomplete
query(`CQT Cat---CALL()`); // ok, but no autocomplete
query(`CQT MyAwesomeChimera---CALL()`); // ok, but no autocomplete
query(`CQT Horse---CALL()`); // ok but should be error
// basically, the query string is typed as: `CQT ${string}---CALL()`
// which is not good
I saw the "nameof" operator proposal and I hope that is not the "answer".