반환 유형을 숫자로 사용하여 함수 인터페이스를 정의하면 컴파일러가 경고합니다.
interface RequestHandler {
(): number
}
// the compiler will prompt an error
// because " Type '() => boolean' is not assignable to type 'RequestHandler'"
const handler: RequestHandler = function (): boolean {
return false
}
그러나 이렇게하면 컴파일러가 괜찮아 보입니다.
interface RequestHandler {
(): void
}
const handler: RequestHandler = function (): boolean {
return false
}
처음에는 void 반환 유형을 사용하는 함수가 모든 반환 유형을 허용한다고 생각했는데 이는 다음과 같이 잘못되었습니다.
// error TS2322: Type 'boolean' is not assignable to type 'void'
function foo(): void {
return true
}
내 가정이 타당하지 않다고 생각합니다. 누구든지 그러한 행동을 설명 할 수 있습니까?
Edit ABOS의 답변은이 동작에 대해 더 많이 찾도록 영감을 얻었습니다. 데모로 새 코드 조각을 올릴 것입니다.
class Animal {
eat() {}
}
// Dog is a subtype of Animal
class Dog extends Animal {
bark() {}
}
interface AnimalBuilder {
(): Animal
}
interface DogBuilder {
(): Dog
}
// DogBuilder is a subtype of Animal Builder
declare let animalBuilder: AnimalBuilder
declare let dogBuilder: DogBuilder
// this demonstrate "co-variance"
animalBuilder = dogBuilder // Ok
dogBuilder = animalBuilder // Error
interface AnimalFeeder {
(animal: Animal): void
}
interface DogFeeder {
(dog: Dog): void
}
// ...while AnimalFeeder is a subtype of DogFeeder (under "strictFunctionTypes")
// this is called "contra-variance"
// Although counter-intuitive at first glance, it ensures stronger type safety
declare let animalFeeder: AnimalFeeder
declare let dogFeeder: DogFeeder
// "contravariance"
dogFeeder = animalFeeder // Ok
animalFeeder = dogFeeder // Error when "--strictFunctionTypes"
// Ok when "strictFunctionTypes" is set to false, bi-variance
내 이해 : 두 가지 유형 호환성 검사가 있습니다.
에 대한
const handler: RequestHandler = function (): boolean {
return false
}
여기서 일어나는 일은 Comparing two functions 에 따라 반환 유형 부울 함수가 void에 할당 될 수 있다는 것 입니다. 이 섹션의 맨 아래에있는 예와 "유형 시스템은 소스 함수의 반환 유형이 대상 유형의 반환 유형의 하위 유형이되도록 강제합니다."라는 문을 참고하십시오. 여기의 경우 void는 부울의 하위 유형입니다.
에 대한
// error TS2322: Type 'boolean' is not assignable to type 'void'
function foo(): void {
return true
}
여기서 일어나는 일은 첫 번째 경우와 달리 데이터 유형 비교입니다. 따라서 예상대로 일치하지 않는 유형에 대해 불평합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다