类型参数名称中的问号是什么

export class Thread {
id: string;
lastMessage: Message;
name: string;
avatarSrc: string;


constructor(id?: string,
name?: string,
avatarSrc?: string) {
this.id = id || uuid();
this.name = name;
this.avatarSrc = avatarSrc;
}
}

id?中,?是用来干什么的?

271160 次浏览

这是为了使variable of可选类型。否则声明的变量显示“未定义的”如果这个变量没有被使用。

export interface ISearchResult {
title: string;
listTitle:string;
entityName?: string,
lookupName?:string,
lookupId?:string
}

parameter?: typeparameter: type | undefined的缩写

那么有什么不同呢?问号表示“可选”。
更准确地说,parameter?: type等于parameter: type | undefined = undefined

参数中的?表示一个可选参数。Typescript编译器不需要填写此参数。查看下面的代码示例了解更多细节:

// baz: number | undefined means: the second argument baz can be a number or undefined


// = undefined, is default parameter syntax,
// if the parameter is not filled in it will default to undefined


// Although default JS behaviour is to set every non filled in argument to undefined
// we need this default argument so that the typescript compiler
// doesn't require the second argument to be filled in
function fn1 (bar: string, baz: number | undefined = undefined) {
// do stuff
}


// All the above code can be simplified using the ? operator after the parameter
// In other words fn1 and fn2 are equivalent in behaviour
function fn2 (bar: string, baz?: number) {
// do stuff
}






fn2('foo', 3); // works
fn2('foo'); // works


fn2();
// Compile time error: Expected 1-2 arguments, but got 0
// An argument for 'bar' was not provided.




fn1('foo', 3); // works
fn1('foo'); // works


fn1();
// Compile time error: Expected 1-2 arguments, but got 0
// An argument for 'bar' was not provided.

从TypeScript 4.7开始,编译器是这样处理这些场景的:

interface OptTest {
test: string
test2: string
test3?: string
test4?: string | null
test5: string | null
test6: null
}


const testVar: OptTest = {}
// Type '{}' is missing the following
// properties from type 'OptTest': test, test2, test5, test6