interface IRecordOption{
format?: 'mp3'|'aac'
}
const recordOption = { format: 'mp3'};
const recorder = {
start(options: IRecordOption): void{
}
}
recorder.start(recordOption)
上面代碼,調用 start() 函數,報傳參類型錯誤。
錯誤消息:
[ts]
Argument of type '{ format: string; }' is not assignable to parameter of type 'IRecordOption'.
Types of property 'format' are incompatible.
Type 'string' is not assignable to type '"mp3" | "aac" | undefined'.
雖然 recordOption.format 的值確實是 'mp3',但定義時,沒有指定類型,在後面代碼引用時,format 的類型是默認的 string 而不是字面量 'mp3',因此,使用前,必須定義爲 IRecordOption 類型,或進行類型轉換。
// 使用強類型
const recordOption:IRecordOption = { format: 'mp3'};
// 或直接進行類型轉換
recorder.start(<IRecordOption>recordOption)