Create type for err-code (#45504)

* feat: err-code

* feat(err-code): handle null correctly

* feat(err-code): add minimum ts requirement
This commit is contained in:
George Zhao 2020-06-21 18:02:12 +10:00 committed by GitHub
parent 692ca9b97a
commit 33dc44bb1d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 103 additions and 0 deletions

View File

@ -0,0 +1,55 @@
import errCode = require('err-code');
// test create without code
const err1 = errCode(new Error('err msg'), {
prop1: 'prop1 value',
prop2: {
a: 'prop2.a value',
}
});
const err1Message = err1.message;
const err1MProp1 = err1.prop1;
const err1MProp2a = err1.prop2.a;
// test create with code
const err2 = errCode(new Error('err msg'), 'Bad Request', {
prop1: 'prop1 value',
prop2: {
a: 'prop2.a value',
}
});
const err2Message = err2.message;
const err2MProp1 = err2.prop1;
const err2MProp2a = err2.prop2.a;
const err2Code = err2.code;
// test adding type constraint
const err3 = errCode<{
prop1: string
prop2: {
a: string
}
}>(new Error('err msg'), {
prop1: 'prop1 value',
prop2: {
a: 'prop2.a value',
}
});
const err3Message = err3.message;
const err3MProp1 = err3.prop1;
const err3MProp2a = err3.prop2.a;
// test null code
const err4 = errCode(new Error('err msg'), null, {
prop1: 'prop1 value',
prop2: {
a: 'prop2.a value',
}
});
const err4Message = err4.message;
const err4MProp1 = err4.prop1;
const err4MProp2a = err4.prop2.a;

24
types/err-code/index.d.ts vendored Normal file
View File

@ -0,0 +1,24 @@
// Type definitions for err-code 2.0
// Project: https://github.com/IndigoUnited/js-err-code#readme
// Definitions by: George <https://github.com/zorji>
// Cayman <https://github.com/wemeetagain>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Minimum TypeScript Version: 3.2
type Scalar = number | string | boolean | bigint | null | undefined;
declare function createError<Props extends object = object, Err extends Error = Error>(
error: Err,
props?: Props,
): Err & Props;
declare function createError<Code extends Scalar = Scalar, Props extends object = object, Err extends Error = Error>(
error: Err,
code: Code,
props?: Props,
): Err & Props & { code: NonNullable<Code> };
declare namespace createError {
}
export = createError;

View File

@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictFunctionTypes": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"err-code-tests.ts"
]
}

View File

@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }