Tuesday, June 16, 2020

how to implement a simple typesafe assertion library in Typescript?

we can assert typesafe to ensure that parameters with specific type in typescript.

here i will demostrate a simple function to ensure that input parameters are the same type

type is={
    <T>(aTb:T):boolean
}

let isSame:is=<T>(
    first:T,
    second:T
)=>{
    return first==second;
}

function print(b:boolean){
    console.log(b);
}

print(isSame("string","anotherString"));
print(isSame(true,false));
print(isSame(4242));
print(isSame(10'foo'));

src/index.ts:73:18 - error TS2345: Argument of type '"foo"' is not assignable to parameter of type 'number'.

73 print(isSame(10, 'foo'));
                    ~~~~~


Found 1 error.




we can easily get the catch the error in compile time. that is the magic of typesafe in typescript, the compiler enforce the type-safe check in the compile time. 



No comments:

Post a Comment