ما الغرض من علامة الاستفهام في اسم معلمة في TypeScript


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?، ما هو الغرض من ?؟

الإجابة رقم 1

يتم ذلك لتحديد المعامل على أنه اختياري.

  • دليل TypeScript https://www.typescriptlang.org/docs/handbook/2/functions.html#optional-parameters
  • استكشاف TypeScript بعمق https://basarat.gitbook.io/typescript/type-system/functions#optional-parameters

الإجابة رقم 2

parameter?: type هو اختصار لـ parameter: type | undefined

فما الفرق؟ علامة الاستفهام تعني "اختياري".
وبشكل أدق، parameter?: type تساوي parameter: type | undefined=undefined

الإجابة رقم 3

هذا لجعل المتغير من النوع الاختياري. وإلا فإن المتغيرات المعلنة تظهر "غير معرفة" إذا لم يتم استخدام هذا المتغير.

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

الإجابة رقم 4

رمز ? في المعلمات يشير إلى معلمة اختيارية. لا يتطلب مترجم 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.