typeScript 中的 ! ?
!的用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| { let y: number; let a: string; y = null!; y = undefined!; a = null!;
console.log('y', y); console.log('a', a); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| { interface IDemo { x?: number; }
let y: number; const demo = (param: IDemo) => { y = param.x!; return y; }; console.log('demo----->', demo({ x: 2 })); }
|
成员
1 2 3 4 5 6 7 8 9
|
class A implemented B { name!: string }
interface B { name?: string }
|
强制链式调用(断言)
1 2 3 4 5 6
|
new Error().stack.split('\n');
new Error().stack!.split('\n');
|
? 用法
除了表示 可选
参数外,常常用于防御性编程
1 2 3 4 5 6 7
| { const a = { b: { c: 0 } } || {}; const tableData = a.b.c; const testData = a?.b?.c; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| { interface IDemo { x: number; }
let y: number;
const demo2 = (parma?: IDemo): number => { y = parma?.x!; console.log('parma?.x---->', parma?.x); return y; };
console.log('demo2----->无参', demo2()); console.log('demo2----->有参', demo2({ x: 7 })); }
|
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| { interface SquareConfig { color?: string; width?: number; } const createSquare = ( config?: SquareConfig ): { color: string; area: number } => { const newSquare = { color: 'red', area: 100 };
if (config?.color) { newSquare.color = config.color; } if (config?.width) { newSquare.area = config.width * config.width; } return newSquare; }; console.log( 'createSquare---->传部分参数属性', createSquare({ color: 'black' }) ); console.log('createSquare---->传空对象参数', createSquare({})); console.log('createSquare---->无参', createSquare()); }
|
结语
永远不要相信苦难是值得的,苦难就是苦难,苦难不会带来成功,苦难不值得追求,磨炼意志是因为苦难无法躲开