메인 콘텐츠로 건너뛰기

TypeScript 가이드

Dropup은 TypeScript로 작성되었으며 포괄적인 타입 정의를 제공합니다.

기본 사용법

import { useDropup } from '@samithahansaka/dropup';
import type { DropupFile, UseDropupOptions } from '@samithahansaka/dropup';

function Uploader() {
const { files, actions, state } = useDropup({
accept: 'image/*',
maxSize: 10 * 1024 * 1024,
});

// files는 DropupFile[]입니다
// actions는 DropupActions입니다
// state는 DropupState입니다

return (
// ...
);
}

타입 가져오기

import type {
// 핵심 타입
DropupFile,
DropupState,
DropupActions,
DropupError,

// 옵션 & 설정
UseDropupOptions,
UploadConfig,
CustomUploader,
ValidationRule,

// 상태 타입
FileStatus,
DropupStatus,

// 반환 타입
UseDropupReturn,

// 유효성 검사
ValidationError,
} from '@samithahansaka/dropup';

타입이 지정된 옵션

const options: UseDropupOptions = {
accept: ['image/*', 'application/pdf'],
maxSize: 10 * 1024 * 1024,
maxFiles: 5,

upload: {
url: '/api/upload',
method: 'POST',
headers: {
'Authorization': 'Bearer token',
},
},

onFilesAdded: (files: DropupFile[]) => {
console.log('추가됨:', files);
},

onUploadComplete: (file: DropupFile, response: unknown) => {
console.log('완료:', file.uploadedUrl);
},

customRules: [
(file: File): boolean | string => {
if (file.name.length > 100) {
return '파일 이름이 너무 깁니다';
}
return true;
},
],
};

const { files, actions, state } = useDropup(options);

타입 안전 콜백

import type { DropupFile, DropupError, ValidationError } from '@samithahansaka/dropup';

const options: UseDropupOptions = {
onFilesAdded: (files: DropupFile[]) => {
files.forEach(file => {
console.log(file.id); // string
console.log(file.name); // string
console.log(file.size); // number
console.log(file.status); // FileStatus
});
},

onValidationError: (errors: ValidationError[]) => {
errors.forEach(({ file, errors }) => {
console.log(file.name); // File.name
console.log(errors); // string[]
});
},

onUploadError: (file: DropupFile, error: DropupError) => {
console.log(error.code); // string
console.log(error.message); // string
console.log(error.cause); // Error | undefined
},
};

커스텀 업로더 타입

import type { CustomUploader, UploadOptions, UploadResult } from '@samithahansaka/dropup';

const myUploader: CustomUploader = async (
file, // DropupFile
options // UploadOptions
): Promise<UploadResult> => {
const { signal, onProgress } = options;

// 업로드 로직...
onProgress(50);

return {
url: 'https://example.com/uploaded-file',
response: { id: '123' },
};
};

useDropup({
upload: myUploader,
});

유효성 검사 규칙 타입

import type { ValidationRule } from '@samithahansaka/dropup';

// 동기 규칙
const checkFilename: ValidationRule = (file: File) => {
if (file.name.includes('draft')) {
return '초안 파일은 허용되지 않습니다';
}
return true;
};

// 비동기 규칙
const checkServer: ValidationRule = async (file: File) => {
const exists = await fetch(`/api/check?name=${file.name}`);
if (await exists.json()) {
return '파일이 이미 존재합니다';
}
return true;
};

useDropup({
customRules: [checkFilename, checkServer],
});

제네릭 Drop Zone Props

import { useDropup } from '@samithahansaka/dropup';

function TypedDropZone() {
const { getDropProps, getInputProps } = useDropup();

// getDropProps에 대한 요소 타입 지정
const dropProps = getDropProps<HTMLDivElement>({
className: 'dropzone',
'data-testid': 'upload-zone',
});

return (
<div {...dropProps}>
<input {...getInputProps()} />
</div>
);
}

파일 상태 타입 가드

import type { DropupFile, FileStatus } from '@samithahansaka/dropup';

// 타입 가드 함수
function isUploading(file: DropupFile): file is DropupFile & { status: 'uploading' } {
return file.status === 'uploading';
}

function isComplete(file: DropupFile): file is DropupFile & { status: 'complete' } {
return file.status === 'complete';
}

function hasError(file: DropupFile): file is DropupFile & { status: 'error' } {
return file.status === 'error';
}

// 사용
function FileList({ files }: { files: DropupFile[] }) {
const uploading = files.filter(isUploading);
const completed = files.filter(isComplete);
const failed = files.filter(hasError);

return (
<>
{uploading.map(file => (
<div key={file.id}>
{file.name} - {file.progress}%
</div>
))}
</>
);
}

DropupFile 메타데이터 확장

import type { DropupFile } from '@samithahansaka/dropup';

// 메타데이터 타입 정의
interface CustomMeta {
category: string;
tags: string[];
description?: string;
}

// 타입 단언으로 사용
const { files, actions } = useDropup();

// 타입이 지정된 메타데이터로 업데이트
actions.updateFileMeta(files[0].id, {
category: 'documents',
tags: ['important', 'work'],
} as CustomMeta);

// 타입 단언으로 액세스
const meta = files[0].meta as CustomMeta | undefined;
console.log(meta?.category);

Dropup을 사용한 컴포넌트 Props

import type { DropupFile, DropupState, DropupActions } from '@samithahansaka/dropup';

interface UploaderProps {
onUploadComplete?: (files: DropupFile[]) => void;
maxFiles?: number;
accept?: string | string[];
}

function Uploader({ onUploadComplete, maxFiles, accept }: UploaderProps) {
const { files, state, actions, getDropProps, getInputProps } = useDropup({
maxFiles,
accept,
onAllComplete: onUploadComplete,
});

return (
// ...
);
}

// 파일 미리보기 컴포넌트
interface FilePreviewProps {
file: DropupFile;
onRemove: (id: string) => void;
}

function FilePreview({ file, onRemove }: FilePreviewProps) {
return (
<div>
<span>{file.name}</span>
<span>{file.status}</span>
<button onClick={() => onRemove(file.id)}>제거</button>
</div>
);
}

클라우드 업로더 타입

import { createS3Uploader } from '@samithahansaka/dropup/cloud/s3';
import type { DropupFile } from '@samithahansaka/dropup';

interface PresignedUrlResponse {
url: string;
fields?: Record<string, string>;
}

const s3Uploader = createS3Uploader({
getPresignedUrl: async (file: DropupFile): Promise<PresignedUrlResponse> => {
const response = await fetch('/api/presign', {
method: 'POST',
body: JSON.stringify({
filename: file.name,
contentType: file.type,
}),
});
return response.json();
},
});

Strict Mode 설정

최대 타입 안전성을 위해:

// tsconfig.json
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noUncheckedIndexedAccess": true
}
}

선언 파일

Dropup 타입을 확장해야 하는 경우:

// types/dropup.d.ts
import '@samithahansaka/dropup';

declare module '@samithahansaka/dropup' {
interface DropupFile {
// 커스텀 속성 추가
customField?: string;
}
}

React 컴포넌트 타입

import type { ReactNode, CSSProperties } from 'react';
import type { UseDropupReturn } from '@samithahansaka/dropup';

interface DropZoneProps {
children?: ReactNode;
style?: CSSProperties;
className?: string;
dropup: UseDropupReturn;
}

function DropZone({ children, style, className, dropup }: DropZoneProps) {
const { getDropProps, getInputProps, state } = dropup;

return (
<div
{...getDropProps({ style, className })}
data-dragging={state.isDragging}
>
<input {...getInputProps()} />
{children}
</div>
);
}