What does ?? and ?: and ?. and !. mean in TypeScript?
Knowledge Callback (Look here if you don’t understand!)
Knowledge column | column link |
---|---|
TypeScript knowledge column | https://blog.csdn.net/xsl_hr/category_12030346.html?spm=1001.2014.3001.5482 |
For related knowledge about TypeScript, you can go to the TypeScript knowledge column to review! !
Scene recurrence
Recently, in the process of in-depth learning at the front end , I came into contact withnetwork requestrelated content, so it is planned to use three columns (HTTP、Axios、Ajax) and piecemeal article summary to record recent study notes. Since the scripting language of the front-end technology stack of the project is TypeScript
, when studying the code of the asynchronous request packaging part of the applet, I encountered a few small TypeScript
knowledge points that were not clear.
Screenshot of problem code:
Therefore, this articleWith TypeScript
neutrality ??
and ?:
harmony as the main ?.
content!.
Expand the explanation.
Core dry goods
??
?:
Refers tooptional parameters- can be understood asparameters are added automatically
undefined
function echo(x: number, y?: number) {
return x + (y || 0);
}
getval(1); // 1
getval(1, null); // error, 'null' is not assignable to 'number | undefined'
interface IProListForm {
enterpriseId: string | number;
pageNum: number;
pageSize: number;
keyword?: string; // 可选属性
}
?:
??
||
The meaning is somewhat similar to , but a little different??
Compared with more||
rigorous,When the value is equal to 0 || just exclude him, but??
not
console.log(null || 5) //5
console.log(null ?? 5) //5
console.log(undefined || 5) //5
console.log(undefined ?? 5) //5
console.log(0 || 5) //5
console.log(0 ?? 5) //0
?.
?.
The meaning is basically the same as &&a?.b
equivalent toa && a.b ? a.b : undefined
const a = {
b: {
c: 7 }
};
console.log(a?.b?.c); //7
console.log(a && a.b && a.b.c); //7
!.
!.
means to assert , to tell ts youThere must be some value in this object
const inputRef = useRef<HTMLEInputlement>(null);
// 定义了输入框,初始化是null,但是你在调用他的时候相取输入框的value,这时候dom实例一定是有值的,所以用断言
const value: string = inputRef.current!.value;
// 这样就不会报错了
That's all aboutWhat does ??
sum ?:
and ?.
sum mean in TypeScript ?!.
Knowledge sharing, I believe that the friends who have read this article must have gained something. Of course, there may be shortcomings, and you are welcome to leave a message in the comment area to correct me!