请教TS的泛型条件约束问题?

演示代码:https://tsplay.dev/N5jo0m

interface Base {
    name: string;
    age: number;
};

interface FixedInstance extends Base {}
interface FollowInstance extends Base {}

type NameType = "fixed"|"follow";

type FixedName = "fixed";
type FollowName = "follow";

const data: NameType = 'fixed';

type myType = typeof data;

type isFixed = myType extends FixedName ? true : false;   // true
type isFollow = myType extends FollowName ? true : false;   // false

// -----------cut---

function sellect<T extends NameType, U = T extends FixedName ? FixedInstance : FollowInstance>(name: T, data: U) {
    return {
        name, data
    };
}



const { name: myName, data: myData } = sellect("fixed", { name: "levi", age: 18 } as FollowInstance);

type dataType = typeof myData;

type dataisFixed = myType extends FixedName ? true : false;   // true
type dataisFollow = myType extends FollowName ? true : false;   // false

cut以上,可以看到都是正确的,问题在函数sellect

  • 我需要根据第一个参数name: T去判断第二个参数data的类型
  • 提供的namefixed就限制dataFixedInstance,否则就限制为FollowInstance

问题1:我在sellect参数传参的时候故意 as FollowInstance,在TS中并没有报错
问题2:在拿到的结果中dataisFixedtrue,但是我传过去的是FollowInstance

阅读 536
1 个回答

修改如下

interface Base {
    name: string;
    age: number;
};

interface FixedInstance extends Base {}
interface FollowInstance extends FixedInstance {
    sex: 1|2;
}

type NameType = "fixed"|"follow";

type FixedName = "fixed";
type FollowName = "follow";

const data: NameType = 'fixed';

type myType = typeof data;

type isFixed = myType extends FixedName ? true : false;   // true
type isFollow = myType extends FollowName ? true : false;   // false

// -----------cut---

function sellect<T extends NameType>(name: T, data: T extends FixedName ? FixedInstance : FollowInstance) {
    return {
        name, data
    } as const;
}

const infodata: FixedInstance = { name: "levi", age: 18 };
const { name: myName, data: myData } = sellect("follow", infodata);

type dataType = typeof myData;

type dataisFixed = myType extends FixedName ? true : false;   // false
type dataisFollow = myType extends FollowName ? true : false;   // false
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
Microsoft
子站问答
访问
宣传栏