Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

typescript - Defining an interface property as the evaluated version of a generic conditional type

I'm trying to define an interface that has a method with a conditional function definition.

I.e.,

interface Test<T> {
    func: T extends string ? () => string : () => number;
}

class TestClass<T extends string> implements Test<T> {
    func = () => "Cats";
}

I get the error:

Property 'func' in type 'TestClass<T>' is not assignable to the same property in base type 'Test<T>'.
  Type '() => string' is not assignable to type 'T extends string ? () => string : () => number'`

My intention is that TS should know I want () => string because T is declared as extending string. However, it seems to want me to declare a type that covers both sides of the conditional even though (I think) I've already narrowed it.

question from:https://stackoverflow.com/questions/65947618/defining-an-interface-property-as-the-evaluated-version-of-a-generic-conditional

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I've come across this quite a few times, and it looks like the typescript compiler just doesn't support conditional types very well. There's this issue on the typescript repo: https://github.com/microsoft/TypeScript/issues/24929, but it has been closed without a fix.

If you want to keep the TestClass generic, there is no way around an any cast: Playground Link

however, if you can specify the type of TestClass, then this is solvable: Playground Link


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...