web前端全系列 教程
1839个小节阅读:2243.9k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
我们知道。接口具有“option bags” 模式,那我们来看下面的例子
xxxxxxxxxx
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig) {
console.log(config)
}
let mySquare = createSquare({width: 100 });
现在多了一个需求,在传入的参数中,可能会传入未知参数colour
因为有“option bags” 模式,会不会允许我们传入未知参数呢?
xxxxxxxxxx
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig) {
}
let mySquare = createSquare({ colour: "red", width: 100 });
然而,TypeScript 会认为这段代码可能存在 bug
对象字面量会被特殊对待而且会经过“额外属性检查”,你会得到一个错误
xxxxxxxxxx
error: Object literal may only specify known properties, but 'colour' does not exist in type 'SquareConfig'. Did you mean to write 'color'?
我们可以通过添加额外属性的方式解决这个问题
xxxxxxxxxx
interface SquareConfig {
color?: string;
width?: number;
[propName: string]: any;
}
function createSquare(config: SquareConfig) {
console.log(config)
}
let mySquare = createSquare({ colour: "red", width: 100 });
还有最后一种跳过这些检查的方式,这可能会让你感到惊讶,它就是将这个对象赋值给一个另一个变量: 因为 squareOptions
不会经过额外属性检查,所以编译器不会报错
xxxxxxxxxx
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig) {
console.log(config)
}
const squareObj = { colour: "red", width: 100 }
let mySquare = createSquare(squareObj);
要留意,在像上面一样的代码里,你可能不应该去绕开这些检查,这不利于代码可读性与纠错性
实时效果反馈
1. 在TypeScript中,接口的额外属性如何定义:
A [propName: string]: any
B [propName: string]
C [propName]: any
D [propName: string]: string
答案
1=>A