在學(xué)習(xí)TypeScript過程中,遇到一點(diǎn)問題,先看下面的代碼interface SquareConfig {
color?: string;
width?: number;
}function createSquare(config: SquareConfig): {color: string; area: number} { let newSquare = {color: "white", area: 100}; if (config.color) {
newSquare.color = config.color;
} if (config.width) {
newSquare.area = config.width * config.width;
} return newSquare;
}
createSquare({height: 200, width: 100 }); // 報(bào)錯(cuò)/**
之前提問寫的,這里實(shí)際是錯(cuò)誤的
let param = { height: 200 }
createSquare(param); // 正確
*///2月21日 更正let param = { height: 200, width: 100 };
createSquare(param); // 正確接口規(guī)定參數(shù)只能傳color, width;而我傳入了height,所以出錯(cuò)了。但是在TypeScript中文網(wǎng)額外的類型檢查一節(jié)中,給出了代碼中規(guī)避編譯器報(bào)錯(cuò)的解決方法。我的困惑是,為什么這種方法能規(guī)避編譯器類型檢查?
TypeScript繞過編譯器檢查的一點(diǎn)困惑
喵喵時(shí)光機(jī)
2019-03-08 12:14:25