0

I'm trying to build a function that returns a typed object through a function that explicility is passed the type

https://stackblitz.com/edit/typescript-uahcrj?file=types.ts

export interface M<TS = any> {
    name?: string;
    state: TS;
}

export const createModel = <TS>() => <
    TM extends M<TS>
>(
    mo: TM
): TM => mo

export type SharksType = {
    values: number[]
    amount: number
}


export const sharks = createModel<SharksType>()({
    state: {
        values: [],
        amount: 1,
    },
})

Actually, amount is correctly infered, but complex states like number[], it's defined like any[],

how can i do dynamically on every key of the state an as?

state: {
        values: [] as number[],
        amount: 1 as number,
    },

1 Answer 1

1

Here's how I would refactor that while sticking with your example - I think you can simplify it quite a bit. Here is a codesandbox for the below: https://codesandbox.io/s/6xd37?file=/index.ts:0-363

The main thing being to type your createModel function. Before you were relying on inference there and you need to define that the function is generic to use the type parameter.

interface CommonModel<T> {
    name?: string;
    state: T;
}

type SharksType = {
    values: number[]
    amount: number
}

const createModel: <T>() => (mo: CommonModel<T>) => CommonModel<T> = () => (mo) => mo;


const sharks = createModel<SharksType>()({
    state: {
        values: [],
        amount: 1,
    },
});

sharks.state.values.push('str'); // error
Sign up to request clarification or add additional context in comments.

4 Comments

Amazing mate, actually i'm struggling a bit with complex types. Do you recommend any book or tutorial? =)
Official docs, SO questions, and Github issues - those would generally be my preferred places to learn. Oh and just experimenting in TS playground helps.
How could i solve that i need the part of extending the Model, TM extends M<TS>, this part is necessary to all the code I got, but the values on the state are not infered.
Hard to say not understanding why you need it - you should include all relevant code so if that piece is needed because of some other code you should include it...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.