gpt4 book ai didi

typescript :从字符串类型中通用删除类型

转载 作者:行者123 更新时间:2023-12-04 01:03:46 24 4
gpt4 key购买 nike

我有一个简单的

type ExampleType = 'a' | 'b' | 'c';

使用方式如下:

from(from: ExampleType) {
return {
to: (to: ExampleType) => {
// move something from/to
},
}
}

我试图让“to-Function”只接受不是在参数“from”中传递的值的值。我尝试使用 Omit 和 Exclude,但它们都不接受动态值。

这可以用 typescript 实现吗?

我想像这样使用它

move(something).from('a').to('b'); // .to() should only accept 'b' and 'c'

这真的很好,IDE 会为此提出正确的建议吗

最佳答案

我相信这可以满足您的需求:使用 T extends ExampleType然后Exclude<ExampleType, T>

type ExampleType = 'a' | 'b' | 'c';

const from = <T extends ExampleType>(from: T) => {
return {
to: (to: Exclude<ExampleType, T>) => {
// move something from/to
},
}
}

from('a').to('b'); // good
from('a').to('c'); // good
from('a').to('a'); // TypeError

TypeScript Playground

关于 typescript :从字符串类型中通用删除类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67229969/

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