Skip to content

Commit 70338a8

Browse files
authored
fix: improve typings for native module error (#479)
1 parent e09ad1e commit 70338a8

File tree

3 files changed

+29
-11
lines changed

3 files changed

+29
-11
lines changed

.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,3 +58,7 @@ android/keystores/debug.keystore
5858

5959
# generated by bob
6060
lib/
61+
62+
63+
# gh-md-toc
64+
docs/gh-md-toc

example/src/App.tsx

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ export default function App() {
1818
console.log(JSON.stringify(result, null, 2))
1919
}, [result])
2020

21-
const handleError = (err: Error) => {
21+
const handleError = (err: unknown) => {
2222
if (DocumentPicker.isCancel(err)) {
2323
console.warn('cancelled')
2424
// User cancelled the picker, exit any dialogs or menus and move on
@@ -33,12 +33,15 @@ export default function App() {
3333
<View style={styles.container}>
3434
<Button
3535
title="open picker for single file selection"
36-
onPress={() => {
37-
DocumentPicker.pickSingle({
38-
presentationStyle: 'fullScreen',
39-
})
40-
.then((pickerResult) => setResult([pickerResult]))
41-
.catch(handleError)
36+
onPress={async () => {
37+
try {
38+
const pickerResult = await DocumentPicker.pickSingle({
39+
presentationStyle: 'fullScreen',
40+
})
41+
setResult([pickerResult])
42+
} catch (e) {
43+
handleError(e)
44+
}
4245
}}
4346
/>
4447
<Button

src/index.tsx

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -146,11 +146,22 @@ export function releaseSecureAccess(uris: Array<string>): Promise<void> {
146146
const E_DOCUMENT_PICKER_CANCELED = 'DOCUMENT_PICKER_CANCELED'
147147
const E_DOCUMENT_PICKER_IN_PROGRESS = 'ASYNC_OP_IN_PROGRESS'
148148

149-
export function isCancel(err: Error & { code?: string }): boolean {
150-
return err?.code === E_DOCUMENT_PICKER_CANCELED
149+
export type NativeModuleErrorShape = Error & { code?: string }
150+
151+
export function isCancel(err: unknown): boolean {
152+
return isErrorWithCode(err, E_DOCUMENT_PICKER_CANCELED)
153+
}
154+
155+
export function isInProgress(err: unknown): boolean {
156+
return isErrorWithCode(err, E_DOCUMENT_PICKER_IN_PROGRESS)
151157
}
152-
export function isInProgress(err: Error & { code?: string }): boolean {
153-
return err?.code === E_DOCUMENT_PICKER_IN_PROGRESS
158+
159+
function isErrorWithCode(err: unknown, errorCode: string): boolean {
160+
if (err instanceof Error && 'code' in err) {
161+
const nativeModuleErrorInstance = err as NativeModuleErrorShape
162+
return nativeModuleErrorInstance?.code === errorCode
163+
}
164+
return false
154165
}
155166

156167
export default {

0 commit comments

Comments
 (0)