TypeScript는 이 유형을 추론할 수 있습니다.
함수에서 this의 기본 유형
이것은 객체의 함수에 있습니다
const obj ={
a:1,
b:2,
fun:function(){
console.log(this.a)
}
}
obj.fun()
분명히 이것은 다음을 가리킨다.
- 1단계: tsc --init, makefile
- 2단계, 노트 열기
- 이것을 모호하게 두지 마십시오. 이것을 가리키도록 지정해야 합니다.
- 이것은 더 엄격해질 것입니다. 이것은 문맥에 따라 이것 자체로 추론되는 유형입니다.
- 이것은 맥락이 없습니다. 파생할 수 없는 경우 엄격 모드에서는 이를 흐리게 하는 것이 허용되지 않으므로 오류가 보고됩니다.
이 유형을 지정하는 방법
- 함수의 첫 번째 매개변수는 나중에 호출되는 함수의 상황에 따라 this의 유형을 선언하는 데 사용될 수 있습니다.
- 함수에 대한 후속 호출에서 매개변수를 전달할 때. 두 번째 매개변수를 전달하면 이 매개변수는 컴파일 후에 삭제됩니다.
function fun( this:{
name:string},info:{
name:string}){
console.log(this)
}
fun.call({
name:"名字"},{
name:"第二个名字"})
이 관련 내장 도구
유형 변환
- TS는 일반적인 유형 변환을 지원하는 몇 가지 도구를 제공하며 이러한 유형은 전 세계적으로 사용 가능합니다.
이매개변수 유형<>
- 이는 함수 유형을 추출하는 데 사용됩니다.
- 이것이 없으면 알 수 없는 결과가 반환됩니다.
이매개변수 유형<>
- 함수 유형 유형의 이 매개변수 유형을 제거하고 현재 함수 유형을 반환하고 싶습니다.
function fun( this:{
name:string},info:{
name:string}){
console.log(this)
}
type funtype = typeof fun
type thisType= ThisParameterType<funtype>
type thisRemove= OmitThisParameter<funtype>
export{
}
이 유형
- 이 유형의 컨텍스트를 표시하는 데 사용됩니다.
- 원래 방법
type User = {
name: string
age: number
}
type Intype = {
User: User
getname: () => void
getage: () => void
}
const username: Intype = {
User: {
name: "乞力马扎罗",
age: 18
},
getname: function (this:User) {
console.log(this.name)
},
getage: function (this:User) {
console.log(this.age)
}
}
username.getname.call(username.User)
username.getage.call(username.User)
export {
}
type User = {
name: string
age: number
}
type Intype = {
User: User
getname: () => void
getage: () => void
}
const username: Intype & ThisType<User> = {
User: {
name: "乞力马扎罗",
age: 18
},
getname: function () {
console.log(this.name)
},
getage: function () {
console.log(this.age)
}
}
username.getname.call(username.User)
username.getage.call(username.User)
export {
}