Microsoft/TypeScript
在 GitHub 查看[Regression] Circular reference error when passing a class expression with non-primitive static properties to a generic function
Open
#59,271 建立於 2024年7月14日
BugDomain: check: Type CircularityHelp Wanted
倉庫指標
- Star
- (48,455 star)
- PR 合併指標
- (平均合併 6天 17小時) (30 天內合併 9 個 PR)
描述
🔎 Search Terms
class expression static type
🕗 Version & Regression Information
- This changed between versions 4.0.5 and 4.1.5
⏯ Playground Link
💻 Code
declare function returnInput<T>(input: T): T;
const a = returnInput(class A {
static foo = {}
// ^?
})
🙁 Actual behavior
A.foo: any
Error: 'foo' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.(7022)
And also note that this bug only happens when the type of foo is not a primitive type.
🙂 Expected behavior
A.foo: {}, as it works in 4.0.5
Additional information about the issue
To define a React class component, it is a common practice to include its "sub-components" as private static properties. I also use a "observer" function to make the state change auto observed. So the real-world code may look like:
import { observer } from 'mobx-react';
import { styled } from 'styled-components';
@observer
class ListView extends React.Component {
// render method here...
private static readonly Item = observer(class Item extends React.Component {
private static readonly Header = styled.h4` // <- Cannot infer the type of Header
// CSS style here...
`;
})
}
A workaround is to use static block to initialize the static property but it's cumbersome:
const a = returnInput(class A {
static foo
// ^? OK
static { this.foo = {}; }
})