gpt4 book ai didi

typescript - 使用方法后类型推断从未知类型变为已知类型

转载 作者:行者123 更新时间:2023-12-05 03:21:56 30 4
gpt4 key购买 nike

我有一个带有单个泛型的类 T , 有时它可以用一个值构造 T是已知的,有时构造时没有值,因此 Tunknown .如果没有给出可以推断类型的值,则必须指定类型是很乏味的。

这归结为我在需要 T 的更复杂类中遇到的确切问题在未保存值时不为未知,因为它可以在以后保存。

class Foo<T> {
value:T;

constructor(value?:T) {
if(value != null && value != undefined) {
this.value = value;
}
}

public set(value:T) {
this.value = value;
}
}

const fn1 = ():Foo<number> => {
const foo = new Foo(0); //foo is Foo<number>
foo.set(1);

return foo; //No error
}

const fn2 = ():Foo<number> => {
const foo = new Foo(); //foo is Foo<unknown>
foo.set(1);
//unknown accepts number apparently and such there is no type collision
//However, I want foo to be re-evaluated to be Foo<number>

return foo; //Error
//const foo: Foo<unknown>
//Type 'Foo<unknown>' is not assignable to type 'Foo<number>'.
// Type 'unknown' is not assignable to type 'number'.
}

const fn3 = ():Foo<number> => new Foo(); //No error, is inferred as being Foo<number>

我是否遗漏了一些东西来允许将泛型类型重新评估为非 unknown

或者,有没有办法让它永远不为人所知?这样如果我做 new Foo()它会要求指定一个类型。 (此外,这不是最好的工作,但 Foo<any> 可以转换为 Foo<number> ,所以有没有办法让 any 成为默认值?)

我知道一个解决方案就是做 new Foo<number>() ,但是,这感觉就像 TypeScript 应该能够推断并且不需要指定它,这确实增加了可能不必要的额外工作。

最佳答案

is there a way I could make it such that any is default?

是的,只需使用 default type对于您的通用:

class Foo<T = any> {}

Playground Link

关于typescript - 使用方法后类型推断从未知类型变为已知类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72862039/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com