Skip to content

Instantly share code, notes, and snippets.

@shubham-vunet
Last active December 28, 2022 07:40
Show Gist options
  • Save shubham-vunet/a8c217ac820eb3fefe1af76772d09890 to your computer and use it in GitHub Desktop.
Save shubham-vunet/a8c217ac820eb3fefe1af76772d09890 to your computer and use it in GitHub Desktop.
Use `unknown` with typechecks and avoid `as`
function test(p: unknown | unknown[]) {
/** Wrong */
if (p as unknown as string[]) {
console.log('p isn\'t string, but executed', p);
/** p is not type safe here, we have to use as everytime */
p as unknown as string[]
}
/** Better */
if (Array.isArray(p) && typeof p[0] === 'string') {
const z0 = p[0]; // p[0] is inferred as string
try{
const z1 = p[1]; // p[1] is inferred as any, might throw error of element doesn't exist
} catch(e){
console.error(e)
}
} else {
throw 'Invalid data, should be string array';
}
/** Not the best, But safe (suggest me best) */
if (Array.isArray(p) && p.every(a => typeof a === 'string')) {
const newArr: string[] = p; // Here p is any[], but after assignment It is type safe and we have already tested it is string
const z0 = p[0]; // p[0] is inferred as any
const n0 = newArr[0]; // p[0] is inferred as any
// We could also check length of array
try{
const z1 = p[1]; // p[1] is inferred as any // might throw error of element doesn't exist
const n1 = newArr[1]; // p[1] is inferred as any // might throw error of element doesn't exist
}catch(e){
console.error(e);
}
} else {
throw 'Invalid data, should be string array';
}
}
// test({});
// test('Hello');
// test(['Hello', {}]);
test(['Hello']);
test(['Hello', 'HI' ]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment