here i will demostrate a simple function to ensure that input parameters are the same type
type is={
<T>(a: T, b: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(42, 42));
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