在 Typescript 中,如何在解构中使用断言?
type StringOrNumber = string | number
const obj = {
foo: 123 as StringOrNumber
}
const { foo } = obj
Run Code Online (Sandbox Code Playgroud)
我没有找到number
在 const 上添加类型断言的便捷方法foo
。两个解决方法是:
// A:
const { foo } = obj as { foo: number }
// B:
const { foo: foo2 } = obj
const foo = <number>foo2
Run Code Online (Sandbox Code Playgroud)
obj
第一个是当 的类型是嵌套且复杂时重写 的类型的负担。第二个看起来很奇怪。我假设这样的语法:
const { <number>foo } = obj
Run Code Online (Sandbox Code Playgroud)
绝对可以帮助我们从嵌套和复杂的解构中断言类型。
我想获取渲染方法的纯文本而不将其渲染到 DOM 中:
class Test from React.Component {
getPlainText = () => {
const plainText = /* some method */(this.renderParagraph())
console.log(plainText) // output in console: <p>I'm text from props of Text component!</p>
}
renderParagraph () {
return <p>{this.props.text}</p>
}
render () {
return <button onClick={this.getPlainText}>click me will print {this.props.text} in console</button>
}
}
Run Code Online (Sandbox Code Playgroud)
我没有找到可能的 React 或 ReactDom API 来完成这个要求。
我通过本指南https://basarat.gitbooks.io/typescript/content/docs/types/type-compatibility.html#types-of-arguments提出了这个问题。
示例代码:
/** Type Heirarchy */
interface Point2D { x: number; y: number; }
interface Point3D { x: number; y: number; z: number; }
/** Two sample functions */
let iTakePoint2D = (point: Point2D) => { /* do something */ }
let iTakePoint3D = (point: Point3D) => { /* do something */ }
iTakePoint3D = iTakePoint2D; // Okay : Reasonable
iTakePoint2D = iTakePoint3D; // Okay : WHAT
Run Code Online (Sandbox Code Playgroud)
显然,iTakePoint2D
的签名与iTakePoint3D不兼容。我们将其用作iTakePoint2D({ x: 100, y: 200 })
,然后它会导致运行时错误,程序无法访问point.z的值。