Fix type narrowing for non empty array
This commit is contained in:
parent
9265e9072d
commit
6d4f32287f
2 changed files with 29 additions and 10 deletions
|
|
@ -384,7 +384,7 @@ is.oddInteger = isAbsoluteMod2(1);
|
|||
|
||||
is.emptyArray = (value: unknown): value is never[] => is.array(value) && value.length === 0;
|
||||
|
||||
is.nonEmptyArray = (value: unknown): value is [unknown, ...unknown[]] => is.array(value) && value.length > 0;
|
||||
is.nonEmptyArray = <T = unknown>(value: T | T[]): value is [T, ...T[]] => is.array(value) && value.length > 0;
|
||||
|
||||
is.emptyString = (value: unknown): value is '' => is.string(value) && value.length === 0;
|
||||
|
||||
|
|
|
|||
37
test/test.ts
37
test/test.ts
|
|
@ -1448,16 +1448,35 @@ test('is.nonEmptyArray', t => {
|
|||
assert.nonEmptyArray(new Array()); // eslint-disable-line @typescript-eslint/no-array-constructor
|
||||
});
|
||||
|
||||
// https://github.com/sindresorhus/is/issues/174
|
||||
// {
|
||||
// const strings = ['foo', 'bar']
|
||||
// const function_ = (value: string) => value;
|
||||
{
|
||||
const strings = ['🦄', 'unicorn'];
|
||||
const function_ = (value: string) => value;
|
||||
|
||||
// if (is.nonEmptyArray(strings)) {
|
||||
// const value = strings[0]
|
||||
// function_(value);
|
||||
// }
|
||||
// }
|
||||
if (is.nonEmptyArray(strings)) {
|
||||
const value = strings[0];
|
||||
function_(value);
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
const mixed = ['🦄', 'unicorn', 1, 2];
|
||||
const function_ = (value: string | number) => value;
|
||||
|
||||
if (is.nonEmptyArray(mixed)) {
|
||||
const value = mixed[0];
|
||||
function_(value);
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
const arrays = [['🦄'], ['unicorn']];
|
||||
const function_ = (value: string[]) => value;
|
||||
|
||||
if (is.nonEmptyArray(arrays)) {
|
||||
const value = arrays[0];
|
||||
function_(value);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('is.emptyString', t => {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue