当前位置:网站首页>Typescript null and undefined

Typescript null and undefined

2022-06-11 07:59:00 YY little monster

Details visible
1.null and undefined

TypeScript There are two special types , null and  undefined, They have value respectively null and undefined.
 By default, we can set  null and  undefined Assign to any type 
 By default null and  undefined You can also assign values to each other 
 Be careful :  In enterprise development ,  If you don't want to put  null and  undefined Assign to other types 
         Or don't want  null and  undefined Assign values to each other ,  Then we can open strictNullChecks


 If we turn it on strictNullChecks,  I also want to put null and  undefined Assign to other types 
 Then we must use union types when declaring 

let value:(number | null | undefined);
value = null;
value = undefined;

 For optional attributes and optional parameters ,  If it's on strictNullChecks,  By default, the data type is a union type 
 It's the current type  + undefined type 
//name The type is (string|null|undefined)
class Person {
    
    name?:string
}
//age The type is (number|null|undefined)
function say(age?:number) {
    

}

2. Remove null and undefined Detection of
Use ! To remove null and undefined

function getLength(value:(string | null | undefined)) {
    
    value = 'abc';
    return ()=>{
    
        // return value.length; //  Report errors 
        // return (value || '').length;
        // return (value as string).length;
        //  We can use ! To remove null and undefined
        // ! The meaning of this variable is that this variable must not be null and undefined
        return value!.length;
    }
}
let fn = getLength('lihui.66666');
let res = fn();
console.log(res);
原网站

版权声明
本文为[YY little monster]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110754014472.html