小编y2b*_*2bd的帖子

精确扩展联合类型

假设有以下示例代码:

type Action = "GET" | "POST" | "PUT";
type Handler<A extends Action> = (action: A) => void;

const handlers: Partial<Record<Action, Handler<Action>>> = { };

function register<A extends Action>(action: A, handler: Handler<A>) {
    /*
    Error:
    Type 'Handler<A>' is not assignable to type 'Partial<Record<Action, Handler<Action>>>[A]'.
        Type 'Handler<A>' is not assignable to type 'Handler<Action>'.
            Type 'Action' is not assignable to type 'A'.
            'Action' is assignable to the constraint of type 'A', but 'A' could be instantiated with a different subtype of constraint …
Run Code Online (Sandbox Code Playgroud)

typescript

7
推荐指数
1
解决办法
4723
查看次数

从typescript方法中获取方法名称

我想从Typescript中的类的实例方法中获取当前方法的名称.

(伪代码,不起作用):

class Foo {
    bar() {
        console.log(something); //what should something be?
    }
}

new Foo().bar();
Run Code Online (Sandbox Code Playgroud)

我希望'某事'能够回归'酒吧'.我意识到this可以给我这个类,我可以以某种方式从它获得类及其属性,但我不知道如何获得'这个函数'(即方法栏,而不是类Foo).

我已经看到了几个与查找类名等有关的问题,但没有找到解决当前方法名称的问题.

javascript typescript

6
推荐指数
1
解决办法
8505
查看次数

TypeScript泛型仅在简单情况下才能推断联合类型

这是一个代码示例:

declare function test_ok<T>(arr: T[]): T;
test_ok([1, 2, "hello"]); // OK
test_ok([[1], [2], ["hello"]]); // OK

// note the nested array signature
declare function test_err<T>(arr: T[][]): T;
test_err([[1], [2], ["hello"]]); // ERR type "string" is not assignable to type "number"
test_err<string | number>([[1], [2], ["hello"]]); // OK if generic is specified
Run Code Online (Sandbox Code Playgroud)

在一般情况下,当给定异构数组时,TypeScript能够推断出最佳的通用类型(基本并集)。但是,如果您尝试将泛型的作用域扩展到除简单数组(例如上面的嵌套数组)之外的任何范围,它就会放弃。我还发现其他情况(例如,泛型在函数的返回类型而不是整个函数之上的函数数组)。这是某种性能优化吗?

typescript

5
推荐指数
1
解决办法
49
查看次数

标签 统计

typescript ×3

javascript ×1