かなり一般的にType string is not assignable to type "foo"というエラーを受け取ります。次の例はこれを示しています。
functioniTakeFoo(foo:'foo') { }consttest= { someProp:'foo'};iTakeFoo(test.someProp); // Error: Argument of type string is not assignable to parameter of type 'foo'
/** Utility function to create a K:V from a list of strings */functionstrEnum<Textendsstring>(o:Array<T>): {[KinT]:K} {returno.reduce((res, key) => { res[key] = key;return res; },Object.create(null));}
そして、keyof typeofを使ってリテラル型の合成を生成します。完全な例を次に示します。
/** Utility function to create a K:V from a list of strings */functionstrEnum<Textendsstring>(o:Array<T>): {[KinT]:K} {returno.reduce((res, key) => { res[key] = key;return res; },Object.create(null));}/** * Sample create a string enum *//** Create a K:V */constDirection=strEnum(['North','South','East','West'])/** Create a Type */typeDirection=keyoftypeof Direction;/** * Sample using a string enum */let sample:Direction;sample =Direction.North; // Okaysample ='North'; // Okaysample ='AnythingElse'; // ERROR!