Skip to content
New issue

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

TypeScript warning/errors #138

Closed
towry opened this issue May 29, 2020 · 4 comments
Closed

TypeScript warning/errors #138

towry opened this issue May 29, 2020 · 4 comments

Comments

@towry
Copy link
Owner

towry commented May 29, 2020

Type 'string' cannot be used to index type 'T'

microsoft/TypeScript#31661

@towry
Copy link
Owner Author

towry commented Jun 4, 2020

协变, 逆变

截屏2020-06-04 16 43 59

ITreeNode 是一个 interface,FormatterRenderItem 是一个实现,但是增加了其他的属性。这个callback函数会被调用者传入一个实现 ITreeNode 接口的类型,但是我们定义这个callback的时候,给的是 FormatterRenderItem。但是 ITreeNode 类型的对象是不能赋值给 FormatterRenderItem 类型的对象,因为前者缺少一些后者定义的属性。我们定义了一个和FormatterRenderItem工作的callback,但是给callback传递参数的行为我们无法控制,假如传递了一个另外一个实现ITreeNode的类型对象,可能会在 callback 里报错的,因为我们可能在callback里调用了 <FormatterRenderItem>.test(),这个 test ITreeNode 没有定义,其他实现者可能也不会定义,就算定义了,行为也可能不一样。


@towry
Copy link
Owner Author

towry commented Jun 5, 2020

microsoft/TypeScript#283 (comment)


(JSDoc) Workaround / for future reference: use manual cast /** @type {name} */ (ref).

// cloneNode produces Node, @see https://github.com/Microsoft/TypeScript/issues/283
var a = document.cloneNode(true);
a.location; // Property 'location' does not exist on type 'Node'.
// workaround:
var b = /** @type {Document} */ (document.cloneNode(true));
b.location; // OK

@towry
Copy link
Owner Author

towry commented Jun 7, 2020

'this' type is available only in a non-static member of a class or interface.

The wrong code:

class Base {
    hooks: {
        // raise error here.
        self: SyncHook<[this]>;
    }
}

The correct code:

interface Hooks<C> {
    self: SyncHook<[C]>;
}

class Base {
    hooks: {
    } & Hooks<this>;
}

@towry
Copy link
Owner Author

towry commented Jun 23, 2020

Get type of generic property.

type Foo<T> = T extends { NodeC: infer U } ? { NodeC: U } : never;

class LinkedList {
    private dummyNode: Foo<this>["NodeC"];

    constructor() {
        const NodeC = this.NodeC;
        this.dummyNode = new NodeC();
    }

    private NodeC = class {
        constructor() {

        }
    }
}

const list = new LinkedList();
console.log(list);

@towry towry closed this as completed Jul 16, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant