Typescript에서 오류를 발생시키는 함수를 선언하는 방법
자바에서는 다음과 같은 함수를 선언합니다.
public boolean Test(boolean test) throws Exception {
if (test == true)
return false;
throw new Exception();
}
그리고 이 기능은 예외 없이 사용할 수 있습니다.
가능한 경우, Typescript에서 같은 작업을 수행하는 방법은 무엇입니까?컴파일러는 try/catch가 없으면 함수를 사용할 수 없다고 말합니다.
TypeScript에는 이러한 기능이 없습니다.오류 유형을 지정할 수 있는 것은 함수가 오류를 반환하지 않고 반환하는 경우뿐입니다(이는 거의 발생하지 않으며 반작용이 발생하기 쉽습니다).
관련된 유일한 유형은 입니다.이는 함수가 확실하게 오류를 발생시키는 경우에만 해당되며, 이보다 더 구체적일 수 없습니다.다른 타입과 마찬가지로 타입의 문제가 발생하지 않는 한 타입 에러는 발생하지 않습니다.
function Test(): never => {
throw new Error();
}
Test(); // won't cause type error
let test: boolean = Test(); // will cause type error
함수가 값을 반환할 가능성이 있는 경우never리턴 타입에 의해 흡수됩니다.
함수 서명에 지정할 수 있지만 참고용으로만 사용할 수 있습니다.
function Test(test: boolean): boolean | never {
if (test === true)
return false;
throw new Error();
}
개발자에게 미처리 오류(기능 본문에서 불분명한 경우)가 발생할 수 있다는 힌트를 줄 수 있지만, 이는 유형 확인에는 영향을 주지 않으며 강제할 수 없습니다.try..catch; 이 함수의 유형이 고려됩니다.(test: boolean) => boolean입력 시스템에 의해.
적어도 jsdoc을 사용하여 함수를 표시할 수 있습니다.타이프스크립트 컴파일러에서 정적 분석 오류를 제공하지 않더라도 일부 IDE 또는 린터가 여전히 경고를 보고할 수 있습니다.
/**
* @throws {Error}
*/
function someFunc() {
if (Math.random() < 0.5) throw Error();
}
someFunc();
지금으로서는 불가능하다.이 요청 기능은 https://github.com/microsoft/TypeScript/issues/13219 에서 확인할 수 있습니다.
JavaScript를 처리할 수 있습니다.Error자바로서RuntimeException(예외).JavaScript의Error프로토타입 체인을 복원하기 위해 사용해야 합니다.Error깨트려버려요.이 답변에서도 setProtypeOf의 필요성에 대해 설명합니다.
export class AppError extends Error {
code: string;
constructor(message?: string, code?: string) {
super(message); // 'Error' breaks prototype chain here
Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain
this.name = 'AppError';
this.code = code;
}
}
순수 ts(v<3.9)는 사용할 수 없습니다.앞으로 사용할 수 있으면 좋겠습니다.회피책은 가능하지만 메서드의 시그니처에 있는 던질 수 있는 유형을 숨기고 캐치 블록에서 해당 유형을 복구하는 것으로 구성됩니다.이 회피책으로 패키지를 만들었습니다.https://www.npmjs.com/package/ts-throwable/v/latest
사용방법은 다음과 같습니다.
import { throwable, getTypedError } from 'ts-throwable';
class CustomError extends Error { /*...*/ }
function brokenMethod(): number & throwable<CustomError> {
if (Math.random() < 0.5) { return 42 };
throw new CustomError("Boom!");
}
try {
const answer: number = brokenMethod()
}
catch(error){
// `typedError` is now an alias of `error` and typed as `CustomError`
const typedError = getTypedError(error, brokenMethod);
}
이 토픽에 관한 흥미로운 PR입니다.https://github.com/microsoft/TypeScript/pull/40468
이 PR의 개요:
- 새로운 유형 수준 표현식: throw type_expr.현재 throw 타입은 인스턴스화 중인 경우에만 throw합니다.
- 유형을 인쇄하기 위한 새로운 고유 유형 TypeToString
알 수 수 있는 은 른른른 of, 자자 is is is is is of of of of of of이다.never기능을 슬로우라고 마크하는 방법은 없지만 유틸리티 타입을 사용하여 알기 쉽게 할 수 있습니다.
type Result<OK = any> = OK | never;
또는 더욱 두드러지게 할 수 있습니다.
type Result<OK = any, Error = never> = OK | Error;
다시 말씀드리지만, 이는 눈으로만 볼 수 있는 것이며, 시행/획득 차단을 강제할 방법은 없습니다.오류를 강제로 처리하려면 약속을 사용하십시오.
기능적 배경에서 나는 반환 유형에서 예상되는 오류(체크된 예외)를 지정하는 것을 선호한다.활자 조합과 활자 가드를 사용하면 다음과 같이 간단합니다.
class ValidationError {
constructor(readonly message: string) {}
static isInstance(err: unknown): err is ValidationError {
if (err === undefined) return false
if (typeof err !== 'object') return false
if (err === null) return false
return err instanceof ValidationError
}
}
function toInt(num: string): number | ValidationError {
const result = Number.parseInt(num)
if (result === undefined) return new ValidationError(`Invalid integer ${num}`)
return result
}
// caller
const result = toInt("a")
if (ValidationError.isInstance(result))
console.log(result.message)
else
console.log(`Success ${result}`)
이렇게 함수의 시그니처는 다른 개발자에게 잠재적인 오류를 강조 표시합니다.더 중요한 것은 IDE와 트랜스필러가 개발자에게 (대부분의 경우) 그들과 거래하도록 강요한다는 것입니다.예를 들어, 이 조작은 실패합니다.
const result = toInt("a")
const doubled = result * 2
error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type
TypeScript는 아니지만, JavaScript의 또 다른 타입 체커인 Hegel이 이 기능을 가지고 있을 수 있습니다.다음과 같이 쓸 수 있습니다.
function Test(test: boolean): boolean | $Throws<Exception> {
if (test)
return false;
throw new Exception();
}
https://hegel.js.org/docs/magic-types#throwserrortype 를 참조해 주세요.
언급URL : https://stackoverflow.com/questions/49434751/how-to-declare-a-function-that-throws-an-error-in-typescript
'source' 카테고리의 다른 글
| 일반 상태 비저장 구성 요소 반응 유형?또는 일반 기능 인터페이스를 더 일반적이 되도록 타이프스크립트로 확장합니까? (0) | 2023.02.22 |
|---|---|
| MUI 스타일로 소품 전달 (0) | 2023.02.18 |
| TypeScript에서 인터페이스 파일 정의를 기반으로 개체를 만들려면 어떻게 해야 합니까? (0) | 2023.02.16 |
| Django REST Framework를 사용하여 POST를 심플하게 하는 방법CSRF 토큰이 없거나 잘못되었습니다. (0) | 2023.02.16 |
| string | null 형식의 인수는 string 유형의 파라미터에 할당할 수 없습니다.유형 'null'은 유형 'string'에 할당할 수 없습니다. (0) | 2023.02.16 |
