Type guards for function in TypeScript -
i've defined type filter in typescript, can string, regexp or predicator, function. type defines listed below.
export type predicator = (input: string) => boolean; export type singlefilter = string | regexp | predicator; there's function taking singlefilter input. however, type guards seems not working predicator, long regexp presists. issue gone if type string | predicator only.
function singlepredicator(value: any) { if (typeof value === 'string') { // string } else if (value instanceof regexp) { // } else { // function // error ts2349: cannot invoke expression type lacks call signature. value(foo); } } is there solution make work in case? thanks. i'm using tsc 1.5.3
the first change in example below have typed value paramater singlefilter rather `any.
the second change type assertion in last else statement hint compiler value predicator.
export type predicator = (input: string) => boolean; export type singlefilter = string | regexp | predicator; function singlepredicator(value: singlefilter) { if (typeof value === 'string') { // string return value.charat(0); } else if (value instanceof regexp) { // value.test("something"); } else { // function var foo = "somefoo"; value(foo); } }
Comments
Post a Comment