We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
正常情况下:
interface Square { kind: 'square'; size: number; } interface Rectangle { kind: 'rectangle'; width: number; height: number; } type Shape = Square | Rectangle; function size(s: Shape) { // 基于 联合类型 和 kind 特殊字面量 // 如果我们用了判断语句,ts会自动帮我们缩小类型范围 if (s.kind === 'square') { return s.size * s.size } // 这里ts推断出 s 是 Rectangle return s.width * s.height }
不符合预期的一种情况:
interface Square { kind: 'square'; size: number; } interface Rectangle { kind: 'rectangle'; width: number; height: number; } type Graph = { [key: string]: Square | Rectangle } function size(s: Graph, key: string) { if (s[key].kind === 'square') { return s[key].size * s[key].size // Error } return s[key].width * s[key].height // Error }
对于不符合逾期的情况有点不解,为什么ts对于这种情况推断不出来呢?
The text was updated successfully, but these errors were encountered:
No branches or pull requests
正常情况下:
不符合预期的一种情况:
对于不符合逾期的情况有点不解,为什么ts对于这种情况推断不出来呢?
The text was updated successfully, but these errors were encountered: