打字稿中的“?:”和“:”符号有什么区别
What is the difference between "?:" and ":" symbols in Typescript
在下面的TypeScript语言接口声明中
使用了“?:”和“:”符号,我无法理解这两个符号之间的区别。我是 Typescript 的新手所以请帮助我。
interface SquareConfig {
color?: string;
width: number
}
interface SquareConfig {
color?: string;
width: number
}
表示color
是可选的属性。
let x: SquareConfig = {
// allowed to omit color without getting a compilation error
width: 10
}
当您使用 ?:
在接口中声明 属性 时,这意味着 属性 是可选的。当您将该接口分配给一个变量时,不必为该 属性 分配值。
例如-
export interface myClass {
name: string,
age?: string
}
在组件中,您必须为 name
属性 赋值,但由于 age
属性 是可选的,因此不需要
values: myClass = {
name: 'john'
// age field is not required
}
在下面的TypeScript语言接口声明中 使用了“?:”和“:”符号,我无法理解这两个符号之间的区别。我是 Typescript 的新手所以请帮助我。
interface SquareConfig {
color?: string;
width: number
}
interface SquareConfig {
color?: string;
width: number
}
表示color
是可选的属性。
let x: SquareConfig = {
// allowed to omit color without getting a compilation error
width: 10
}
当您使用 ?:
在接口中声明 属性 时,这意味着 属性 是可选的。当您将该接口分配给一个变量时,不必为该 属性 分配值。
例如-
export interface myClass {
name: string,
age?: string
}
在组件中,您必须为 name
属性 赋值,但由于 age
属性 是可选的,因此不需要
values: myClass = {
name: 'john'
// age field is not required
}