Typecript에 "Class" 타입이 있습니까?"아무것도"가 포함되어 있나요?
Java에서는 "Class" 형식을 사용하여 메서드에 매개 변수로 클래스를 부여할 수 있습니다.타이프스크립트 문서에서 유사한 것을 발견하지 못했습니다. 메소드에 클래스를 전달할 수 있나요?그렇다면, "아무" 유형에 그러한 클래스 유형이 포함되어 있습니까?
배경:웹스톰에 문제가 있어서 클래스를 다음으로 넘길 수 없다고 합니다.@ViewChild(...)
각2에서.그러나 Typescript 컴파일러는 불평하지 않습니다.의 서명.@ViewChild()
인것 같습니다"Type<any> | Function | string"
, 그래서 클래스가 포함된 것이 있는지 궁금합니다.
당신이 타이프스크립트에서 요구하는 것과 동일한 것은 유형입니다.{ new(): Class }
, 예를 들어 다음과 같습니다.
class A {}
function create(ctor: { new(): A }): A {
return new ctor();
}
let a = create(A); // a is instanceof A
(운동장 코드)
위의 코드는 생성자가 인수가 없는 클래스만 허용합니다.원하는 수업이 있으면 다음을 사용합니다.new (...args: any[]) => Class
가장 간단한 해결책은let variable: typeof Class
.
여기에 예가 있습니다.
class A {
public static attribute = "ABC";
}
function f(Param: typeof A) {
Param.attribute;
new Param();
}
f(A);
각도 내부 신고 Type
다음과 같이:
export interface Type<T> extends Function { new (...args: any[]): T; }
TypeScript3을 사용하면 함수 오버로드 없이 인수에 대한 유형을 추가할 수 있습니다.
export interface TypeWithArgs<T, A extends any[]> extends Function { new(...args: A): T; }
예:
class A {}
function create(ctor: Type<A>): A {
return new ctor();
}
let a = create(A);
메소드에 클래스를 주는 것이 가능합니까?그렇다면, "아무" 유형에 그러한 클래스 유형이 포함되어 있습니까?
네, 네.any
모든 유형을 포함합니다.
클래스만 포함하는 유형의 예는 다음과 같습니다.
type Class = { new(...args: any[]): any; };
그런 다음 사용:
function myFunction(myClassParam: Class) {
}
class MyClass {}
myFunction(MyClass); // ok
myFunction({}); // error
다음에 대한 클래스 전달 오류가 없어야 합니다.Function
잘 작동할 것이기 때문입니다.
var func: Function = MyClass; // ok
Type<T>
로부터@angular/core
클래스에 적합한 인터페이스입니다.
export interface Type<T> extends Function {
new (...args: any[]): T;
}
이 클래스 대신 클래스를 참조하는 데 사용할 수 있습니다.
private classRef: Type<MyCustomClass>;
아니면
private classRef: Type<any>;
당신의 질문 배경에 의하면.@ViewChild
:
@ViewChild를 통해 주입 가능"string selector"
/Component
/Directive
의 서명Type<any> | Function | string
위의 모든 것을 주입할 수 있는 추상적인 서명입니다.
다음이 제게 도움이 되었습니다.
type ClassRef = new (...args: any[]) => any;
사용 사례:
interface InteractionType { [key: string]: ClassRef; }
클래스만 포함하는 유형의 예는 다음과 같습니다.
declare type Class<T = any> = new (...args: any[]) => T;
사용하지 않고 다른 해결책이 있습니다.typeof
:
타이프스크립트에 다음과 같은 유틸리티 유형이 있습니다.InstanceType
, 그 선언은 다음과 같습니다.
type InstanceType<T extends abstract new (...args: any) => any> = T extends abstract new (...args: any) => infer R ? R : any
다음 코드를 사용하여 자신의 클래스 유형을 선언할 수 있습니다.
interface ClassType<InstanceType extends {} = {}> extends Function {
new(...args: any[]): InstanceType
prototype: InstanceType
}
언급URL : https://stackoverflow.com/questions/39392853/is-there-a-type-for-class-in-typescript-and-does-any-include-it
'it-source' 카테고리의 다른 글
클래스 사용 시기 vs.PHP에서의 기능 (0) | 2023.09.18 |
---|---|
사용자 지정 작업 창은 어떻게 UI의 반응성을 유지하면서 가시성을 전환할 수 있습니까? (0) | 2023.09.18 |
다른 컨테이너에서 도커 컨테이너 액세스 (0) | 2023.09.18 |
변경 유형별 필터 git diff (0) | 2023.09.13 |
대량 삽입 기능이 있는 AWS RDS의 네트워크 성능 문제 (0) | 2023.09.13 |